<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------

namespace app\api\model;

use app\api\controller\Common;
use app\api\controller\KbxOrder;
use app\api\controller\Product;
use think\Cookie;
use think\Db;
use think\Cache;
use think\db\Expression;
use think\Exception;
use think\exception\DbException;
use \think\Model;
use app\api\model\Goods as G;
use app\api\model\GroupToursLine as GT;
use app\api\controller\KbxOther;
use app\api\controller\KbxToken;
use app\wap\model\Goods as WGoodsModel;
use app\wap\controller\Goods as WapGoodsController;
use app\api\controller\Viator;
use app\api\model\Fareharbor as FModel;
use app\api\controller\FareGoods as F;

class Standard extends Model{
    private $customerAttrs = [];
    //初始化model
    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->customerAttrs = [
            '姓名'=>'姓名-name-1-1-1-1',
            '微信号'=>'微信号-wechat-0-1-0-0',
            '手机号'=>'手机号-mobile-1-1-1-0',
            '身份证号'=>'身份证号-idNo-0-0-0-0',
            '年龄'=>'年龄-age-0-0-0-0',
            '性别'=>'性别-gender-0-0-0-0',
            '体重'=>'体重-weight-0-0-0-0',
            '车型'=>'车型-carType-0-0-0-0',
        ];
    }

    //获取标品列表
    public function getList($post,$page=1,$offset=20,$from='toB')
    {
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品
        $where['s.allow_everyone_quote'] = 1;//允许售卖的产品
        if(isset($post['keyword']) && !empty($post['keyword'])){
            $where['s.name|g.goods_name'] = ['like','%'.$post['keyword'].'%'];//用于搜索
        }
        $city_function = "";
        if(isset($post['fromCityId']) && !empty($post['fromCityId'])){
            $cityId = $post['fromCityId'];//用于搜索
            $city_function = function ($query) use ($cityId) {
                $query->where(function($query) use ($cityId){
                    $query->where(['st.startCityId'=>$cityId,'s.type'=>1]);
                })->whereOr(function($query) use ($cityId){
                    $query->where(['s.startCity'=>$cityId,'s.type'=>2]);
                });
            };
        }
        //顶级分类 【决定筛选条件的内容】
        // topCate=1（景点线路）
        // topCate=2（当地玩乐）

        if(isset($post['topCate']) && !empty($post['topCate'])){
            $where['topCate'] = $post['topCate'];
        }
        //默认没有标签筛选
        $cates = $post['cates']??"";
        if(!empty($cates)) $cates = array_filter(explode(",",$cates));
        if(!empty($cates) && !in_array('-1',$cates)){
            $standardtags = db("standardtags")->where(['tagid'=>['in',$cates]])->field("sid,count(sid) as count");
            if(count($cates)>1){
                $standardtags = $standardtags->having("count > 1");
            }
            $standard_id_arr = $standardtags->group("sid")->select();

            if(!empty($standard_id_arr)){
                $standard_id_arr = array_unique(array_column($standard_id_arr,"sid"));
                $where['s.id'] = ['in',$standard_id_arr];//用于搜索
            }else{
                //未检索到商品
                return [0,[]];
            }
        }

        //中英文服务
        $server_function = [];
        $server = $post['server']??'';
        if(!empty($server) && $server!='-1'){
            $server = explode(',',$server);
            foreach ($server as $key=>$value){
                $server_function[] = ' find_in_set('.$value.',g.tag_id) ';
            }
        }
        $server_function = implode(' or ',$server_function);
        //二次确认
        $other_function = [];
        $other = $post['other']??[];
        if(!empty($other)){
            $other = explode(',',$other);
            foreach ($other as $key=>$value){
                $other_function[] = ' find_in_set('.$value.',g.tag_id) ';
            }
        }
        $other_function = implode(' or ',$other_function);

        $total = db("standard s")
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->where($where)
            ->where($city_function)
            ->where($server_function)
            ->where($other_function)
            ->count();
        $list = db("standard s")
            ->where($where)
            ->where($city_function)
            ->where($server_function)
            ->where($other_function)
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,showImg,g.goods_id,is_recommend,s.introduce,
            trip_id,startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,days,endDays,subType,toursLineTitle,specialInfo')
            ->order("s.is_recommend desc,s.id desc")
            ->page($page,$offset)
            ->select();
//        var_dump(db()->getLastSql());exit;
        foreach ($list as $key=>$value){
            $list[$key]['standardTypeName'] = $this->getTypeName($value['standardType']);
            $list[$key]['subType'] = $this->getSubType($value['subType']);

            //获取关联的商品信息
            $list[$key]['goodsInfo'] = new \ArrayObject();
            $list[$key]['showImg'] = "";
            if(!empty($value['goods_id'])){
                $list[$key]['goodsInfo'] = $this->getLinkGoodsInfo($value['goods_id'],$value['standardId'],$from);
                $image = $list[$key]['goodsInfo']['small_image']??[];
                $list[$key]['showImg'] = $this->checkImgUrl($image[0]??"")??"";
                $list[$key]['goodsprice'] = $list[$key]['goodsInfo']['goodsprice']??"0";
                $list[$key]['salesVolume'] = $list[$key]['goodsInfo']['goodssales']??"0";
                unset($list[$key]['goodsInfo']['small_image']);
                $list[$key]['startCityId'] = $value['startCityId']?:$list[$key]['goodsInfo']['city_id'];
                $list[$key]['startCityName'] = $value['startCityName']?:$list[$key]['goodsInfo']['cityName'];
                $list[$key]['kbxStartCityId'] = $value['kbxStartCityId']?:$list[$key]['goodsInfo']['kbxCityId'];
            }

//            if(!empty($value['image'])){
//                $list[$key]['image'] = array_filter(explode(",",$value['image']));
//            }
//            //获取关联的出发城市和目的城市
//            $list[$key]['from'] = new \ArrayObject();
//            $list[$key]['to'] = new \ArrayObject();
//            if(!empty($value['from_address_json'])) $list[$key]['from']=json_decode($value['from_address_json'],true);
//            if(!empty($value['to_address_json'])) $list[$key]['to']=json_decode($value['to_address_json'],true);

            //组合门票信息
//            $list[$key]['ticket'] = new \ArrayObject();
//            if(!empty($list[$key]['unitTicketPrice'])){
//                $list[$key]['ticket'] = [
//                    'currency'=>$value['ticketCurrency'],
//                    'unitTicketPrice'=>$value['unitTicketPrice'],
//                    'unitTicketDetails'=>$value['unitTicketDetails']
//                ];
//            }
//            //销毁address变量
//            unset($list[$key]['from_address_json'],$list[$key]['to_address_json']);
//            //销毁ticket变量
//            unset($list[$key]['ticketCurrency'],$list[$key]['unitTicketPrice'],$list[$key]['unitTicketDetails']);

        }

        return [$total,$list];
    }

    //获取ES搜索标品列表
    public function getListByES($post,$page=1,$offset=20,$from='toB')
    {
        //默认按推荐排序
        $list = [];

        return [$total,$list];
    }
    //获取标品详情
    public function getDetail($standard_id,$from='toB')
    {
        $where['s.id'] = $standard_id;
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品
        $where['s.type'] = 1;//行程标品专用接口
        $info = db("standard s")
            ->where($where)
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,content,video,goods_id,is_recommend,
            trip_id,startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,days,endDays,subType,toursLineTitle,specialInfo')
            ->find();
        if(empty($info)){
            $info = [];
        }else{
            //标签
            $info['tagsList'] = $this->getTagsList($standard_id);

            //类型
            $info['standardTypeName'] = $this->getTypeName($info['standardType']);
            //获取关联的商品信息和订单类型
            $info['goodsInfo'] = new \ArrayObject();
            //默认订单类型为用车类
            $info['orderType'] = "Vehicle";
            //图片
            $info['image'] = [];
            $info['showImg'] = "";
            if(!empty($info['goods_id'])){
                $info['goodsInfo'] = $this->getLinkGoodsInfo($info['goods_id'],$standard_id,$from);
                $info['orderType'] = $info['goodsInfo']['orderType']??"Vehicle";
                $infoImages = [];
                if(!empty($info['goodsInfo']['small_image'])){
                    foreach ($info['goodsInfo']['small_image'] as $image){
                        $infoImages[] = $this->checkImgUrl($image);
                    }
                }
                $info['image'] = $infoImages;
                $info['showImg'] = $info['image'][0]??"";
                $info['goodsprice'] = $info['goodsInfo']['goodsprice']??"0";
                $info['salesVolume'] = $info['goodsInfo']['goodssales']??"0";
                unset($info['goodsInfo']['orderType'],$info['goodsInfo']['small_image']);
            }
            //销毁ticket变量
            unset($info['ticketCurrency'],$info['unitTicketPrice'],$info['unitTicketDetails']);

            $tripid = $info['trip_id']??0;
            $info['productInfo'] = $this->getProductSection($tripid,$info['orderType']);
            $info['productInfo']['supplierId'] = "";
            if(!empty($info['productInfo']['supplier_admin_id'])){
                $info['productInfo']['supplierId'] = db('supplier_admin')->find($info['productInfo']['supplier_admin_id'])['company_id']??'';
            }
            //组合门票信息
            $ticketList = [];
            $section = $info['productInfo']['section']??[];
            if(!empty($section)){
                foreach ($section as $section_v){
                    if(!empty($section_v['ticket'])){
                        $ticketList = array_merge($ticketList,$section_v['ticket']);
                    }
                }
            }
            $info['ticket'] = $ticketList;
            //获取关联的出发城市和目的城市
            $info['from'] = $info['productInfo']['from']??(new \ArrayObject());
            $info['to'] = $info['productInfo']['to']??((new \ArrayObject()));
            unset($info['productInfo']['from'],$info['productInfo']['to']);
            //获取包车类型 包车类型多中则默认为一日包车
            $info['orderSubType'] = "Transport_Vehicle_OneDay";
            if(isset($info['productInfo']['section_json'])){
                $section_json = $info['productInfo']['section_json'];
                $section_arr = json_decode($section_json,true);
                if(count($section_arr)==1 && isset($section_arr[0]['transport'])){
                    $section_trans = empty($section_arr[0]['transport'])?4:$section_arr[0]['transport'];
                    $info['orderSubType'] = $this->getTransportType($section_trans);
                }
                unset($info['productInfo']['section_json']);
            }
        }

        return $info;
    }

    //获取行程信息
    public function getProductSection($tripid,$orderType)
    {
        $productInfo = db("product")->field("id,name,description,introduction,code,content,section_json,section_trans_json,price as costsInclude,priceno as costsNotInclude,back as returnRules,careful as careNote,supplier_admin_id,customer_content,net_weight,shelf_life,production_date,production_license,storage_conditions,edible_methods,executive_standard_no,is_text_plan,text_plan")->find($tripid);
        $schedules = Db::name('pschedule')->field("id,displayorder,groupid")->where('groupid',$tripid)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)) {
            $activeList = db('pactive a')
                ->join("city c", "c.id=a.cityid", 'left')
                ->join("poi p", "p.id=a.poiid", 'left')
                ->field("a.id,a.title,a.groupid,a.activeType,a.time as startingTime,a.content as remark,a.displayorder,a.title,a.poiid,a.cityid as cityId,c.name as cityName,c.kbx_id as kbxCityId,a.airport_lat,a.airport_lng,p.lat,p.lng,p.name as poiname,a.poiid,p.address,p.place_id,a.ticket_status")
                ->where(['a.groupid' => ['in', $schedule_ids]])
                ->order('a.groupid,a.displayorder')
                ->select();
        }else{
            return [];
        }
        foreach ($schedules as $key=>$value){
            $schedules[$key]['label'] = "第".$value['displayorder']."天";
            $schedules[$key]['children'] = [];
            foreach ($activeList as $k=>$v){
                $v = $this->getAirportInfo($v);
                if($v['groupid']==$value['id']){
                    $v['label'] = empty($v['poiname'])?$v['title']:$v['poiname'];
                    //准备经纬度
                    if(in_array($v['activeType'],[2,3])){
                        $v['lat'] = $v['airport_lat'];
                        $v['lng'] = $v['airport_lng'];
                    }
                    unset($v['airport_lat'],$v['airport_lng']);
                    $schedules[$key]['children'][] = $v;
                }
            }
        }
        //$productInfo['tripData'] = $schedules;
        //筛选行程的起点和终点
        $start_poi = $end_popi = [];
        foreach ($schedules as $key=>$value){
            foreach ($value['children'] as $k=>$v){
                if(!empty($v['lat']) && !empty($v['lng'])){
                    if(empty($start_poi)){
                        $start_poi = $v;
                    }
                    $end_popi = $v;
                }
            }
        }
        $from = $to = new \ArrayObject();
        if(!empty($start_poi)){
            $from = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$start_poi['label'],
                        "addr"=>$start_poi['address'],
                        "lat"=>$start_poi['lat'],
                        "lng"=>$start_poi['lng'],
                        "gid"=>$start_poi['place_id'],
                    ]
                ]
            ];
        }
        if(!empty($end_popi)){
            $to = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$end_popi['label'],
                        "addr"=>$end_popi['address'],
                        "lat"=>$end_popi['lat'],
                        "lng"=>$end_popi['lng'],
                        "gid"=>$end_popi['place_id'],
                    ]
                ]
            ];
        }
        $productInfo['from'] = $from;
        $productInfo['to'] = $to;
        $section_json = json_decode($productInfo['section_json'],true);
        $section_json = !empty($section_json)?$section_json:[];

        if(!empty($section_json)){
            $section = [];
            foreach ($section_json as $section_k=>$section_v){
                $section[] = $this->packageSectionDataPricing($section_v,$schedules,$orderType);
            }
            $day_sort = array_column($section,'day');
            array_multisort($section,SORT_ASC,$day_sort);
            $productInfo['section'] = $section;
        }else{
            return [];
        }
        //删除交通配置json数据【接口不需要显示】
        //unset($productInfo['section_json']);
        $productInfo['isTextPlan'] = empty($productInfo['is_text_plan'])?false:true;
        $productInfo['textPlan'] = $productInfo['text_plan']??'';
        $productInfo['customer_content'] = !empty($productInfo['customer_content'])?json_decode($productInfo['customer_content'],true):[];
        unset($productInfo['section_trans_json'],$productInfo['is_text_plan'],$productInfo['text_plan']);
        return $productInfo;
    }

    //封装单个section 用于用于拆单
    public function packageSectionDataPricing($trans_value,$schedules,$orderType)
    {
        //当前段的包车类型 默认是市内一日包车
        $transport_type = empty($trans_value['transport'])?4:$trans_value['transport'];
        $subType = $this->getTransportType($transport_type);

        //当前段的包车报价
        $start_index = explode("-",$trans_value['start']);
        $end_index = explode("-",$trans_value['end']);
        $section = [];
        $poiList = [];
        if($start_index[0]==$end_index[0]){
            $child = $schedules[$start_index[0]]['children'];
            $length = $end_index[1]-$start_index[1]+1;
            $activeList = array_slice($child,$start_index[1],$length);
            $scheduleList = $schedules[$start_index[0]];
            $scheduleList['children'] = $activeList;
            $section[] = $scheduleList;
            $poiList = $activeList;
        }else{
            for ($i = $start_index[0]; $i <= $end_index[0]; $i++){
                $child = $schedules[$i]['children'];
                if($i < $end_index[0]){
                    $max = count($child);
                    $scheduleList = $schedules[$i];
                    if($i > $start_index[0]){
                        $activeList = array_slice($child,0,$max);
                    }else{
                        $activeList = array_slice($child,$start_index[1],$max);
                    }
                    $poiList += $activeList;
                    $scheduleList['children'] = $activeList;
                }else{
                    $activeList = array_slice($child,0,$end_index[1]+1);
                    $scheduleList = $schedules[$i];
                    $poiList += $activeList;
                    $scheduleList['children'] = $activeList;
                }
                $section[] = $scheduleList;
            }
        }
        //获取标题
        $title = "";
        //门票信息
        $hasTicketPoiId = [];
        foreach ($section as $key=>$value){
            $title .= "第".$value['displayorder']."天:";
            $active_title = array_column($value['children'],"label");
            if(!empty($active_title)){
                $title .= implode("--",$active_title);
            }
            $title .= "\n";

            foreach ($value['children'] as $child_k=>$child_v){
                if($child_v['ticket_status']==1){
                    $hasTicketPoiId[] = $child_v['poiid'];
                }
            }
        }
        //门票信息
        $ticket = $this->getSectionTicketData($hasTicketPoiId);

        //获取起始点和终点的经纬度
        $start_poi = $end_poi = [];
        foreach ($poiList as $key=>$value){
            if(!empty($value['lat']) && !empty($value['lng'])){
                if(empty($start_poi)){
                    $start_poi = $value;
                }
                $end_poi = $value;
            }
        }
        $fromKbxCityId = "";
        $from = $to = new \ArrayObject();
        if(!empty($start_poi)){
            $from = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$start_poi['label'],
                        "addr"=>$start_poi['address'],
                        "lat"=>$start_poi['lat'],
                        "lng"=>$start_poi['lng'],
                        "gid"=>$start_poi['place_id'],
                    ]
                ]
            ];
            $fromKbxCityId = $start_poi['kbxCityId'];
        }
        if(!empty($end_poi)){
            $to = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$end_poi['label'],
                        "addr"=>$end_poi['address'],
                        "lat"=>$end_poi['lat'],
                        "lng"=>$end_poi['lng'],
                        "gid"=>$end_poi['place_id'],
                    ]
                ]
            ];
        }
        $startDay = intval(explode("-",$trans_value['start'])[0]);
        return ['startDay'=>$startDay,'orderType'=>$orderType,'day'=>$trans_value['start'],'from'=>$from,'to'=>$to,'orderSubType'=>$subType,'toursLineTitle'=>$title,'fromCity'=>$fromKbxCityId,'days'=>count($section),'ticket'=>$ticket];
    }
    //获取产品关联的门票信息
    public function getSectionTicketData($hasTicketPoiId)
    {
        $ticket = [];
        $exchangeArr = Db::name("exchange")->select();//汇率
        if(!empty($hasTicketPoiId)){
            $ticketPriceData = db("ticketprice tp")
                ->join("poi p","p.id=tp.poiid",'left')
                ->where(['tp.poiid'=>['in',$hasTicketPoiId],'default'=>1])
                ->field("tp.id,tp.name,tp.sale_price,tp.cost_price,tp.currency,p.name as poiname,p.eng_name as poiengname,tp.charge_type")->select();
            foreach ($ticketPriceData as $ticket_v){
                $exchangeRate = 1;
                foreach ($exchangeArr as $exchange){
                    if($exchange['currency_code']==$ticket_v['currency']){
                        $exchangeRate = $exchange['exchange_rate'];
                    }
                }
                $ticket[] = [
                    'ticketId'=>$ticket_v['id'],
                    'poiName'=>$ticket_v['poiname'].'('.$ticket_v['poiengname'].')',
                    'ticketName'=>$ticket_v['name'],
                    'unitBase'=>[
                        'amount'=>$ticket_v['cost_price'],
                        'currency'=>$ticket_v['currency'],
                    ],
                    'unitPrice'=>intval($ticket_v['cost_price']*$exchangeRate*100)/100,
                    'desc'=>"",
                    'chargeType'=>$ticket_v['charge_type']==2?'vehicle':'human',
                ];
            }
        }

        return $ticket;
    }
    //封装单个section
    public function packageSectionDataUnpackOrder($section)
    {
        $poiList = [];
        //获取标题
        $title = "";
        foreach ($section as $key=>$value){
            $title .= "第".$value['displayorder']."天:";
            $active_title = array_column($value['children'],"label");
            if(!empty($active_title)){
                $title .= implode("--",$active_title);
            }
            $title .= "\n";
            foreach ($value['children'] as $kk=>$vv){
                $poiList[] = $vv;
            }
        }
        //获取起始点和终点的经纬度
        $start_poi = $end_poi = [];
        foreach ($poiList as $key=>$value){
            if(!empty($value['lat']) && !empty($value['lng']) && empty($start_poi)){
                $start_poi = $value;
            }
            if(!empty($value['lat']) && !empty($value['lng'])){
                $end_poi = $value;
            }
        }
        $from = $to = [];
        if(!empty($start_poi)){
            $from = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$start_poi['label'],
                        "addr"=>$start_poi['address'],
                        "lat"=>$start_poi['lat'],
                        "lng"=>$start_poi['lng'],
                        "gid"=>$start_poi['place_id'],
                    ]
                ]
            ];
        }
        if(!empty($end_poi)){
            $to = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$end_poi['label'],
                        "addr"=>$end_poi['address'],
                        "lat"=>$end_poi['lat'],
                        "lng"=>$end_poi['lng'],
                        "gid"=>$end_poi['place_id'],
                    ]
                ]
            ];
        }
        $day = $section[0]['displayorder']??"";
        $day .= "-".$section[0]['children'][0]['displayorder']??"";
        return ['day'=>$day,'form'=>$from,'to'=>$to,'subType'=>"Chartered_Car",'toursLineTitle'=>$title,'tripData'=>$section];
    }

    //获取交通类型 （用于订单系统核价）
    public function getTransportType($type_id)
    {
        $data =  [
            "1"=>"Transport_Vehicle_FromAirport",
            "2"=>"Transport_Vehicle_ToAirport",
            "8"=>"Transport_Vehicle_ShortDistance",
            "3"=>"Transport_Vehicle_HalfDay",
            "4"=>"Transport_Vehicle_OneDay",
            "5"=>"Transport_Vehicle_Around",
            "6"=>"Transport_Vehicle_LongTrip"
        ];

        if(!empty($type_id)){
            return $data[$type_id];
        }else{
            return $data;
        }
    }
    //获取交通类型 用于前端展示
    public function getTransportTitle($type_id = 0)
    {
        $data =  [
            "1"=>"接机",
            "2"=>"送机",
            "8"=>"单程接送",
            "3"=>"市区半日包车",
            "4"=>"市区一日包车",
            "5"=>"周边一日包车",
            "6"=>"长途包车",
        ];

        if(!empty($type_id)){
            return $data[$type_id];
        }else{
            return $data;
        }
    }

    //获取标品标签
    public function getTagsList($standard_id)
    {
        $where['sid'] = $standard_id;
        $standardTags = db("standardtags st")
                        ->join("tag t",'st.tagid=t.tag_id')
                        ->field("t.tag_name")
                        ->where($where)
                        ->select();

        return $standardTags;
    }
    //获取标品类型
    public function getTypeName($type)
    {
        switch ($type){
            case 1:
                $name = "行程标品";
                break;
            case 2:
                $name = "资源标品";
                break;
            default:
                $name = "";
                break;
        }

        return $name;
    }

    //获取商品套餐信息
    public function  getLinkGoodsInfo($goods_id=0,$standard_id=0,$from="toB",$noRate=false)
    {
        if($from=="toB"){
            $field = "goods_tcode,goods_id,goods_name,goods_englishname as goods_ename,goods_introduce,price,orderType,goods_image,goodssales,invented_sold,channel_source,`show`,channel_source,source_id,code as third_code,city_id,merchantCancellable,tag_id as goods_tags,need_confirm";
        }else{
            $field = "goods_tcode,goods_id,goods_name,goods_englishname as goods_ename,goods_introduce,price,orderType,goods_image,goodssales,invented_sold,channel_source,`show`,channel_source,source_id,code as third_code,city_id,merchantCancellable,tag_id as goods_tags,need_confirm";
        }
        $product = db("goods")
            ->field($field)
            ->find($goods_id);
        if(!empty($product['invented_sold'])){
            $product['goodssales'] += $product['invented_sold'];
        }
        if(!empty($product['goods_image'])){
            $product['small_image'] = array_values(array_filter(explode(",",$product['goods_image'])));
            if(!empty($product['small_image'])){
                foreach ($product['small_image'] as $image_k=>$image_v){
                    $product['small_image'][$image_k] = $this->checkImgUrl($image_v);
                }
            }
        }else{
            $product['small_image'] = [];
        }
        //替换里面的图片地址
        $product['goods_introduce'] = $this->replaceUeditorImgUrl($product['goods_introduce']);
        $product['need_confirm'] = !empty($product['need_confirm']) && $product['need_confirm']==1?true:false;
        //价格设置 toB需要折扣
        $discount = 1;
        if($from=="toB"){
            //折扣价
            $discount = $this->getDiscountRatePriceToB($standard_id);
        }

        //产品价格替换
        $product_id = '';
        $product_section = '';
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($product['goods_tcode']) && $product['goods_tcode']!==''){
            $productData = db("product")->where("item_num",$product['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();
            if(!empty($productData) && $productData['base_price_mode']==1){
                $product_id = $productData['id'];
                $product_section = $productData['price_section'];
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($productData) && $productData['new_price_flag']==1){
                $product_id = $productData['id'];
                $product_section = $productData['price_section'];
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        if($product_price_exists==2){
            //从价格表获取价格数据 大于0
            $min_price = db("product_base_dailyprice pd")
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->field("min(pd.price*pd.minorder_num) as goodsprice")
                ->where(['pd.product_id'=>$product_id,'pd.price'=>['gt',0],'ps.special'=>['lt',1]])
                ->find();
            $min_cost = db("product_base_dailyprice pd")
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->field("min(pd.total_cost*pd.minorder_num*100/(100-ps.bdj_rate)) as goodsprice")
                ->where(['product_id'=>$product_id,'total_cost'=>['gt',0],'ps.special'=>['lt',1]])
                ->find();
        }elseif($product_price_exists==1){
            //从价格表获取价格数据 大于0
            $min_price = db("product_dailyprice")
                ->field("min(price*minorder_num) as goodsprice")
                ->where(['product_id'=>$product_id,'price'=>['gt',0]])
                ->find();

        }else{
            //从价格表获取价格数据 大于0
            $min_price = db("personday")
                ->field("min(person_price*minorder_num) as goodsprice")
                ->where(['goods_id'=>$goods_id,'person_price'=>['gt',0]])
                ->find();
        }

        if(!empty($min_price['goodsprice'])){
            if($product_price_exists==2){
                $product['goodsprice'] = sprintf('%.2f',round($min_cost['goodsprice']));
                $product['oldgoodsprice'] = sprintf('%.2f',round($min_price['goodsprice']));
            }else{
                $product['goodsprice'] = sprintf('%.2f',ceil($min_price['goodsprice']*$discount));
                $product['oldgoodsprice'] = sprintf('%.2f',ceil($min_price['goodsprice']));
            }

        }else{
            $product['goodsprice'] = "0.00";
            $product['oldgoodsprice'] = "0.00";
        }
        $product['cityName'] = "";
        $product['kbxCityId'] = "";
        //商品城市
        if(!empty($product['city_id'])){
            $cityInfo = db('city')->field('name,kbx_id,groupid')->find($product['city_id']);
            $product['cityName'] = $cityInfo['name']??"";
            $product['kbxCityId'] = $cityInfo['kbx_id']??"";
        }else{
            $cityInfo['groupid'] = 0;
        }
        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        $currency_code = "USD";//默认美元
        if($cityInfo['groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate']??1;//当地汇率    美元/加元
        //商品类型
        if(!empty($product['third_code']) && $product['show']==2){
            $product['typesource'] = 'viator';
            //价格刷不进来 从远程获取
            if(empty($product['price'])){
                $product['price'] = (new Viator())->goodsDetail($product['third_code'],'price');
            }
            $product['goodsprice'] = ceil($product['price']*$discount*$local_exchange);
            $product['oldgoodsprice'] = ceil($product['price']*$local_exchange);
        }elseif($product['channel_source']=='fareharbor'){
            //获取farehabor利润点
            $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
            $sell_percent_rate = empty($sell_rate)&&$sell_rate['discount_num']?1:$sell_rate['discount_num'];
            if(!empty($product['source_id'])){
                $usd_price_section = db('fareharbor_goods')->field('usd_price_section')->find($product['source_id'])['usd_price_section']??0;
                $usd_price_section = explode('~',$usd_price_section);
                $product['price'] = $usd_price_section[0]??0;
            }
            $product['typesource'] = 'fareharbor';
            $product['goodsprice'] = ceil($product['price']*$discount*$local_exchange*$sell_percent_rate);
            $product['oldgoodsprice'] = ceil($product['price']*$local_exchange*$sell_percent_rate);
        }else{
            //关联产品的价格问题
            if($product_price_exists==2 && !empty($productData['currency']) && $exchangeRate = db('exchange')->where("currency_code",$productData['currency'])->find()){
                $local_exchange = $exchangeRate['exchange_rate']??1;//默认人民币汇率
                $product['goodsprice'] = ceil($product['goodsprice']*$local_exchange);
                $product['oldgoodsprice'] = ceil($product['oldgoodsprice']*$local_exchange);
            }else{
                $product['goodsprice'] = ceil($product['goodsprice']);
                $product['oldgoodsprice'] = ceil($product['oldgoodsprice']);
            }
            $product['typesource'] = 'myself';
        }
        //获取标签
        $product['tags'] = [];
        if(!empty($product['goods_tags'])){
            $product['tags'] = db('tag')
                ->where([
//                        'tag_type'=>2,
                        'tag_status'=>['neq',2],
//                        'tob_show'=>1,//标签展示
                        'tag_id'=>['in',$product['goods_tags']]]
                )
                ->field("tag_id,tag_name,icon")
                ->select();
        }

        unset($product['show'],$product['goods_image'],$product['channel_source'],$product['third_code'],$product['goods_tags']);
        return $product;
    }

    //通过日期和商品id获取套餐价格
    public function getGoodsSpecPriceByDate($standardInfo,$date,$from='toB',$noRate=false)
    {
        $priceList = [];
        $goods_id = $standardInfo['goods_id'];
        $goodsinfo = db("goods")->find($goods_id);
        //价格设置 toB需要折扣
        $discount = 1;
        if($from=="toB"){
            //折扣价
            $discount = $this->getDiscountRatePriceToB($standardInfo['id']);
        }
        if(!empty($goodsinfo)){
            //产品价格替换
            $product_id = '';
            $product_price_exists = 0;//是否存在产品价格
            //存在产品时
            if(!empty($goodsinfo['goods_tcode']) && $goodsinfo['goods_tcode']!==''){
                $product = db("product")->where("item_num",$goodsinfo['goods_tcode'])->field("id,price_section,new_price_flag,extra_fee,extra_fee_desc,base_price_mode")->find();
                if(!empty($product) && $product['base_price_mode']==1) {
                    $product_id = $product['id'];
                    $product_price_exists = 2;//存在产品设置基础价格
                }elseif(!empty($product) && $product['new_price_flag']==1){
                    $product_id = $product['id'];
                    $product_price_exists = 1;//存在产品设置价格
                }
            }
            if($product_price_exists==2){
                //用车类型的返回空

            }elseif($product_price_exists==1){
                //20191127 新增额外成本
                $extra_fee = $product['extra_fee']??"";
                $extra_fee_desc = $product['extra_fee_desc']??"";
                $extra_fee = explode(",",$extra_fee);
                $extra_fee_desc = explode("|",$extra_fee_desc);
                $package = db("product_package")->where(['product_id'=>$product_id])->select();
                if(!empty($package)){
                    $package_id = array_column($package,"id");
                    $specs = db("product_specs")->where(['package_id'=>['in',$package_id]])->select();
                    $specsData = [];
                    if(!empty($specs)){
                        $specs_id = array_column($specs,"id");
                        $priceList = db("product_dailyprice p")
                            ->field('p.package_id as specs_id,p.specs_id as person_id,p.name as person_name,
                        p.num as person_num,p.price as person_price,p.minorder_num,
                        p.inc_order_num,p.carType,p.ticket_car_cost,
                        p.vehicle_cost,p.hotel_cost,p.ticket_cost,p.extra_cost,p.hotel_json,
                        s.vehicle_type as specs_type,pe.minorder_num as people_num,
                        s.name as specs_name')
                            ->join('product_package s','s.id=p.package_id','left')
                            ->join('product_specs pe','pe.id=p.specs_id','left')
                            ->where(['p.specs_id'=>['in',$specs_id],'time'=>$date])
                            ->order("p.specs_id asc")
                            ->select();
                        $currency = $standardInfo['costCurrency']??"";

                        foreach ($priceList as $key=>$value){
                            $priceList[$key]['unit_price'] = sprintf('%.2f',ceil($value['person_price']*$discount));
                            $priceList[$key]['person_price'] = sprintf('%.2f',ceil($value['person_price']*$value['minorder_num']*$discount));
                            $priceList[$key]['old_person_price'] = sprintf('%.2f',ceil($value['person_price']*$value['minorder_num']));
                            $priceList[$key]['carTypeInfo'] = $this->getCarInfo($value['carType']);
                            $priceList[$key]['specs_type'] = !empty($value['specs_type'])?$value['specs_type']:
                                (in_array($value['person_name'],['5座车','7座车','12座车'])?1:0);
                            $priceList[$key]['hotel_json'] = !empty($value['hotel_json'])?json_decode($value['hotel_json'],true):[];
                            foreach ($priceList[$key]['hotel_json'] as $hotel_k=>$hotel_v){
                                //计算价格转换汇率和销售系数之后的值
                                $priceList[$key]['hotel_json'][$hotel_k]['price'] = sprintf('%.2f',ceil($hotel_v['price']*$goodsinfo['hotel_rate']));
                            }
                            //关联的分段的价格
                            $tripid = $standardInfo['trip_id']??0;
                            $recommendedCost = [];
                            $extrasCost = [];
                            if(!empty($tripid)){
                                $psection = db("psection")->where(['product_id'=>$tripid,'car_type'=>$value['carType']])->find();
                                if(!empty($psection) && !empty($psection['section_json'])){
                                    $price_json = json_decode($psection['section_json'],true);
                                    foreach ($price_json as $price_key=>$price_value){
                                        $extra_cost['amount'] = !empty($extra_fee[$price_key])?floatval($extra_fee[$price_key]):0;
                                        $extra_cost['desc'] = $extra_fee_desc[$price_key]??'';
                                        $cost['amount'] = floatval($price_value);
                                        $cost['currency'] = $extra_cost['currency']= $currency;
                                        $recommendedCost[] = $cost;
                                        $extrasCost[] = $extra_cost;
                                    }
                                }
                            }
                            //默认返回一段的价格
                            if(empty($recommendedCost)){
                                $recommendedCost[] = [
                                    'amount'=>0,
                                    'currency'=>$currency
                                ];
                                $extrasCost[] = [
                                    'amount'=>0,
                                    'desc'=>'',
                                    'currency'=>$currency
                                ];
                            }

                            $priceList[$key]['carBase'] = $recommendedCost;
                            $priceList[$key]['extras'] = $extrasCost;
                        }
                        $specsData = [];
                        //组装数据
                        $specs_ids = array_unique(array_column($priceList,'specs_id'));
                        foreach ($specs_ids as $value){
                            $specsData[] = [
                                'specs_id'=>$value,
                            ];
                        }
                        foreach ($priceList as $k=>$v){
                            foreach ($specsData as $key=>$value){
                                if($value['specs_id']==$v['specs_id']){
                                    if(empty($specsData[$key]['specs_name'])){
                                        $specsData[$key]['specs_name'] = $v['specs_name'];
                                    }
                                    unset($v['specs_id'],$v['specs_name']);
                                    $specsData[$key]['child'][] = $v;
                                    break;
                                }
                            }
                        }
                    }

                    return $specsData;
                }
            }else{
                //20191127 新增额外成本
                $extra_fee = $goodsinfo['extra_fee']??"";
                $extra_fee_desc = $goodsinfo['extra_fee_desc']??"";
                $extra_fee = explode(",",$extra_fee);
                $extra_fee_desc = explode("|",$extra_fee_desc);

                $specs = db("specs")->where(['goods_id'=>$goods_id])->select();
                if(!empty($specs)){
                    $specs_id = array_column($specs,"specs_id");
                    $persons = db("person")->where(['specs_id'=>['in',$specs_id]])->select();
                    if(!empty($persons)){
                        $persons_id = array_column($persons,"person_id");
                        $priceList = db("personday p")
                            ->field('p.specs_id,p.person_id,p.person_name,
                        p.person_num,p.person_price,p.minorder_num,
                        p.inc_order_num,p.carType,
                        p.vehicle_cost,p.hotel_cost,p.ticket_cost,p.extra_cost,p.hotel_json,
                        s.vehicle_type as specs_type,pe.people_num,
                        s.specs_name')
                            ->join('specs s','s.specs_id=p.specs_id','left')
                            ->join('person pe','pe.person_id=p.person_id','left')
                            ->where(['p.person_id'=>['in',$persons_id],'time'=>$date])
                            ->order("p.person_id asc")
                            ->select();
                        $currency = $standardInfo['costCurrency']??"";

                        foreach ($priceList as $key=>$value){
                            //$priceList[$key]['total_price'] = $value['person_num']*$value['person_price'];
                            $priceList[$key]['unit_price'] = sprintf('%.2f',ceil($value['person_price']*$discount));
                            $priceList[$key]['person_price'] = sprintf('%.2f',ceil($value['person_price']*$value['minorder_num']*$discount));
                            $priceList[$key]['old_person_price'] = sprintf('%.2f',ceil($value['person_price']*$value['minorder_num']));
                            $priceList[$key]['carTypeInfo'] = $this->getCarInfo($value['carType']);
                            $priceList[$key]['specs_type'] = !empty($value['specs_type'])?$value['specs_type']:
                                (in_array($value['person_name'],['5座车','7座车','12座车'])?1:0);
                            $priceList[$key]['hotel_json'] = !empty($value['hotel_json'])?json_decode($value['hotel_json'],true):[];
                            foreach ($priceList[$key]['hotel_json'] as $hotel_k=>$hotel_v){
                                //计算价格转换汇率和销售系数之后的值
                                $priceList[$key]['hotel_json'][$hotel_k]['price'] = sprintf('%.2f',ceil($hotel_v['price']*$goodsinfo['hotel_rate']));
                            }
                            //关联的分段的价格
                            $tripid = $standardInfo['trip_id']??0;
                            $recommendedCost = [];
                            $extrasCost = [];
                            if(!empty($tripid)){
                                $psection = db("psection")->where(['product_id'=>$tripid,'car_type'=>$value['carType']])->find();
                                if(!empty($psection) && !empty($psection['section_json'])){
                                    $price_json = json_decode($psection['section_json'],true);
                                    foreach ($price_json as $price_key=>$price_value){
                                        $extra_cost['amount'] = !empty($extra_fee[$price_key])?floatval($extra_fee[$price_key]):0;
                                        $extra_cost['desc'] = $extra_fee_desc[$price_key]??'';
                                        $cost['amount'] = floatval($price_value);
                                        $cost['currency'] = $extra_cost['currency']= $currency;
                                        $recommendedCost[] = $cost;
                                        $extrasCost[] = $extra_cost;
                                    }
                                }
                            }
                            //默认返回一段的价格
                            if(empty($recommendedCost)){
                                $recommendedCost[] = [
                                    'amount'=>0,
                                    'currency'=>$currency
                                ];
                                $extrasCost[] = [
                                    'amount'=>0,
                                    'desc'=>'',
                                    'currency'=>$currency
                                ];
                            }

                            $priceList[$key]['carBase'] = $recommendedCost;
                            $priceList[$key]['extras'] = $extrasCost;
                        }
                        $specsData = [];
                        //组装数据
                        $specs_ids = array_unique(array_column($priceList,'specs_id'));
                        foreach ($specs_ids as $value){
                            $specsData[] = [
                                'specs_id'=>$value,
                            ];
                        }

                        foreach ($priceList as $k=>$v){
                            foreach ($specsData as $key=>$value){
                                if($value['specs_id']==$v['specs_id']){
                                    if(empty($specsData[$key]['specs_name'])){
                                        $specsData[$key]['specs_name'] = $v['specs_name'];
                                    }
                                    unset($v['specs_id'],$v['specs_name']);
                                    $specsData[$key]['child'][] = $v;
                                    break;
                                }
                            }
                        }
                    }

                    return $specsData;
                }
            }

        }
        return $priceList;
    }
    /**
     * 获取酒店房价配置
     */
    public function getRoomPrice($standard_id=0)
    {
        $field = "room_id,room_name,room_price,room_person_num";
        $price = db("standard_hotel_config")
            ->field($field)
            ->where(['link_id'=>$standard_id])
            ->order("sort_num desc")
            ->select();
        foreach ($price as $key=>$value){
            $price[$key]['room_price'] = floatval($value['room_price']);
            $price[$key]['total_price'] = $value['room_person_num']*$value['room_price'];
        }
        return $price;
    }
    //获取车辆类型
    //{'1':'5座','10':'7座','15':'8座','20':'12座','30':'15座'}
    public function getCarTypeTitle($subType=0)
    {
        $title = "";
        switch ($subType){
            case 1:
                $title = "5座车";
                break;
            case 10:
                $title = "7座车";
                break;
            case 15:
                $title = "8座车";
                break;
            case 20:
                $title = "12座车";
                break;
            case 30:
                $title = "15座车";
                break;
            default:
                $title = "";
                break;
        }

        return $title;
    }

    //获取包车类型
    public function getSubType($subType=0)
    {
        $title = "";
        switch ($subType){
            case 1:
                $title = "halfday";
                break;
            case 2:
                $title = "oneday";
                break;
            case 3:
                $title = "around";
                break;
            case 4:
                $title = "longtrip";
                break;
            default:
                $title = "";
                break;
        }

        return $title;
    }

    //获取天数的标签
    public function getDaysByTransJson($json_arr,$actives)
    {
        if(empty($json_arr)){
            return [];
        }else{
            foreach ($json_arr as $key=>$value){
                $s_day = explode("-",$value['start'])[0];
                $e_day = explode("-",$value['end'])[0];
                $s_poi = explode("-",$value['start'])[1];
                $e_poi = explode("-",$value['end'])[1];
                $json_arr[$key]['s_day'] = intval($s_day);
                $json_arr[$key]['e_day'] = intval($e_day);
                $s_label = $actives[$s_day]['children'][$s_poi]['label'];
                $e_label = $actives[$e_day]['children'][$e_poi]['label'];
                if($s_label==$e_label){
                    $json_arr[$key]['s_poiname'] = '/';
                }else{
                    $json_arr[$key]['s_poiname'] = $s_label;
                }
                $json_arr[$key]['e_poiname'] = $e_label ;
                if($s_day==$e_day){
                    $json_arr[$key]['day_title'] ='第'.($s_day+1).'天';
                }else{
                    $json_arr[$key]['day_title'] ='第'.($s_day+1).'天至第'.($e_day+1).'天';
                }

                $json_arr[$key]['type_title'] =$this->getTransportTitle($value['type']);
            }
        }
        $sday_arr = array_column($json_arr,"s_day");
        $eday_arr = array_column($json_arr,"e_day");
        array_multisort($sday_arr,SORT_ASC,$eday_arr,SORT_ASC,$json_arr);
        return $json_arr;
    }
    //解构json数据
    public function deconstructTransJson($json_arr,$trip_arr){
        $data = [];
        if(empty($json_arr)){
            return [];
        }else{
            foreach ($json_arr as $key=>$value){
                $s_index = array_search($value['start'],$trip_arr);
                $e_index = array_search($value['end'],$trip_arr);
                if($s_index<$e_index){
                    $section_data = array_slice($trip_arr,$s_index,$e_index-$s_index+1);
                    $data = array_merge($data,$section_data);
                }else{
                    $data[] = $trip_arr[$s_index];
                }
            }
        }
        return $data;
    }
    //获取标品列表
    public function getSearch($keyword="",$from='toB',$page=1,$offset=20)
    {
        if(empty($keyword)){
            return [0,[]];
        }else{
            $where['s.name'] = ['like','%'.$keyword.'%'];
        }
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品

        $total = db("standard s")->where($where)->count();
        $list = db("standard s")->where($where)
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce,showImg,goods_id,is_recommend,
            trip_id,startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,salesVolume,days,endDays,subType,toursLineTitle,specialInfo')
            ->order("sortNum desc");
        if($from!="toB"){
            $list = $list->page($page,$offset);
        }
        $list = $list->select();
        foreach ($list as $key=>$value){
            $list[$key]['standardTypeName'] = $this->getTypeName($value['standardType']);
            $list[$key]['subType'] = $this->getSubType($value['subType']);

            //获取关联的商品信息
            $list[$key]['goodsInfo'] = new \ArrayObject();
            if(!empty($value['goods_id'])){
                $list[$key]['goodsInfo'] = $this->getLinkGoodsInfo($value['goods_id']);
            }
        }

        return [$total,$list];
    }

    //获取车辆类型
    public function getCarTypeList()
    {
        $res = db("car_type")
            ->field("cartype_id,car_value,title")
            ->where(['is_use'=>1])
            ->select();
        return $res;
    }

    //返回包含域名的图片地址
    public function checkImgUrl($url="")
    {
        //返回图片的与名头
        $http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://':"http://";
        $webUrl = $http.$_SERVER['HTTP_HOST'];
        if(empty($url)){
            return "";
        }
        //路径是否包含域名
        $bool = strpos($url,"https://");
        if($bool!==false){
            return $url;
        }else{
            return $webUrl.$url;
        }

    }

    //替换详情里的图片地址
    public function replaceUeditorImgUrl($content)
    {
        //返回图片的与名头
        $http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://':"http://";
        $webUrl = $http.$_SERVER['HTTP_HOST'];

        $content = str_replace("/ueditor/php/upload/image",$webUrl."/ueditor/php/upload/image",$content);
        //重复添加时去重
        return str_replace($webUrl.$webUrl,$webUrl,$content);
    }

    //判断如果是机场节点 需要获取订单系统的机场信息
    public function getAirportInfo($active){
        if(in_array($active['activeType'],[2,3])){//接机和送机
            $airportData = (new KbxOther())->kbxGetAirport($active['cityId']);
            foreach ($airportData as $k=>$v) {
                if($v['id']==$active['poiid']){
                    $active['poiname'] = $v['name'];
                    $active['airport_lat'] = (string)$v['location']['lat'];
                    $active['airport_lng'] = (string)$v['location']['lng'];
                    break;
                }
            }
        }
        return $active;
    }

    //获取套餐日历
    public function getStandardSpecTimeList($goods_id,$standard_id,$from='toB',$noRate=false){
        $goods = db("goods")->where("goods_id",$goods_id)->find();
        //产品价格替换
        $product_id = '';
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();

            if(!empty($product) && $product['base_price_mode']==1){
                $product_id = $product['id'];
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_id = $product['id'];
                $product_price_exists = 1;//存在产品设置价格
            }
        }

        //获取可售卖的时间 截止天数+当前时间
        $standardtrip = db('standardtrip')->where('sid',$standard_id)->find();
        if(!empty($standardtrip['endDays']) && $standardtrip['endDays']>0){
            $sale_time = $standardtrip['endDays']==1?strtotime('+1 day'):strtotime('+'.$standardtrip['endDays'].' day');
        }else{
            $sale_time = time();
        }
        $sale_time = date('Y-m-d',$sale_time);
        if($product_price_exists==2){
            $list = db("product_base_dailyprice")->field('`time`,min(price*minorder_num) as min_price')
                ->where(['product_id'=>$product_id,'time'=>['egt',$sale_time]])
                ->group('time')
                ->order("time asc")
                ->select();


        }elseif($product_price_exists==1){
            $list = db("product_dailyprice")->field('`time`,min(price*minorder_num) as min_price')
                ->where(['product_id'=>$product_id,'time'=>['egt',$sale_time]])
                ->group('time')
                ->order("time asc")
                ->select();
        }else{
            $list = db("personday")->field('`time`,min(person_price*minorder_num) as min_price')
                ->where(['goods_id'=>$goods_id,'time'=>['egt',$sale_time]])
                ->group('time')
                ->order("time asc")
                ->select();
        }
        $discount = 1;
        if($from=='toB'){
            //折扣价
            $discount = $this->getDiscountRatePriceToB($standard_id);
        }
        foreach ($list as $key=>$value){
            $list[$key]['old_min_price'] = ceil($value['min_price']);
            if($product_price_exists==2){
                //关联产品的价格问题
                if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                    $local_exchange = $exchangeRate['exchange_rate']??1;//默认人民币汇率
                    $list[$key]['old_min_price'] = $list[$key]['min_price'] = ceil(round($value['min_price'])*$local_exchange);
                }
            }else{
                //基价模式不考虑折扣
                $list[$key]['min_price'] = ceil($value['min_price']*$discount);
            }

        }

        return $list;
    }

    //获取toB商品的折扣率
    public function getDiscountRatePriceToB($standard_id)
    {
        $discount = 1;
        if(empty($standard_id)){
            return $discount;
        }

        //规则1 按照标品id查找
        $res1 = db("tob_discount")->where(['type'=>1])->where("find_in_set(".$standard_id.",ids_str)")->find();
        if(!empty($res1)){
            return $res1['discount_rate'];
        }
        //规则2 按照标品分类查找
        //景点线路
        $ctypeid1 = db("standardtags st")
            ->field('st.tagid')
            ->join('tag t','st.tagid=t.tag_id','left')
            ->where(['tag_type'=>5,'sid'=>$standard_id])
            ->find();
        $ctypeid2 = db("standardtags st")
            ->field('st.tagid')
            ->join('tag t','st.tagid=t.tag_id','left')
            ->where(['tag_type'=>6,'sid'=>$standard_id])
            ->find();

        if(!empty($ctypeid1['tagid']) && !empty($ctypeid2)){
            $res2 = db("tob_discount")->where(['type'=>0,'ctypeid1'=>$ctypeid1['tagid'],'ctypeid2'=>$ctypeid2['tagid']])->find();
            if(!empty($res2)){
                return $res2['discount_rate'];
            }
        }
        //当地玩乐
        $ctypeid3 = db("standardtags st")
            ->field('st.tagid')
            ->join('tag t','st.tagid=t.tag_id','left')
            ->where(['tag_type'=>8,'sid'=>$standard_id])
            ->find();
        if(!empty($ctypeid3)){
            $res3 = db("tob_discount")->where(['type'=>0,'ctypeid1'=>$ctypeid3['tagid']])->find();
            if(!empty($res3)){
                return $res3['discount_rate'];
            }
        }

        return $discount;
    }

    //获取产品的原始节点数据
    public function getProductScheduleData($tripId)
    {
        $schedules = Db::name('pschedule')->field("id,displayorder,time,groupid")->where('groupid',$tripId)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)) {
            $activeList = db('pactive a')
                ->join("city c", "c.id=a.cityid", 'left')
                ->join("poi p", "p.id=a.poiid", 'left')
                ->field("a.id,a.title,a.poiname,a.groupid,a.activeType,a.time as startingTime,a.content as remark,a.displayorder,a.title,a.poiid,a.cityid as cityId,c.name as cityName,c.kbx_id as kbxCityId,a.airport_lat,a.airport_lng,p.lat,p.lng,a.poiid,a.ticket_status")
                ->where(['a.groupid' => ['in', $schedule_ids]])
                ->order('a.groupid,a.displayorder')
                ->select();
        }
        foreach ($schedules as $key=>$value){
            $schedules[$key]['label'] = "第".$value['displayorder']."天";
            $schedules[$key]['children'] = [];
            foreach ($activeList as $k=>$v){
                //拉取订单系统的城市
                $v = $this->getAirportInfo($v);
                if($v['groupid']==$value['id']){
                    $v['label'] = empty($v['poiname'])?$v['title']:$v['poiname'];
                    $schedules[$key]['children'][] = $v;
                }
            }
        }

        return $schedules;
    }

    /*****************ToB商品***************************/
    public function getGoodsList($post,$page=1,$offset=20,$from='toB',$noRate=false)
    {
        //定义默认数据
        $result = [0,[]];
        $m= new WGoodsModel();
        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        //必须由城市参数
        $fromCityId = $post['city_id']??0;
        if(!empty($fromCityId)){
            $where['city_id'] = $post['city_id'];//用于搜索
            $city= db('city')->where('id',$fromCityId)->find();
            $city_function = function ($query) use ($city) {
                $query->where('city_id','eq',$city['id'])->whereor('city_id','eq',$city['destid'])->whereor("find_in_set('{$city['id']}',belong_city)")->whereor("belong_city = 999999");
            };
        }else{
            $city_function = [];
        }

        //关键词搜素
        if(isset($post['keyword']) && !empty($post['keyword'])){
            $where['g.goods_name'] = ['like','%'.$post['keyword'].'%'];//用于搜索
        }
        //分类筛选
        if(isset($post['classify_id']) && !empty($post['classify_id'])){
            $where['classify_id'] = $post['classify_id'];//用于搜索
        }
        //标签筛选
        if(isset($post['tag_id']) && !empty($post['tag_id'])){
            $where['tag_id'] = $post['tag_id'];
        }
        //是否推荐
        if(isset($post['recommend']) && !empty($post['recommend'])){
            $where['recommend'] = 1;//用于搜索
        }
        //是否热门
        if(isset($post['popular']) && !empty($post['popular'])){
            $where['popular'] = 1;//用于搜索
        }
        //排序条件
        $sort= $post['sort']??"";
        //在售
        $map['goods_status']='1';
        //订单类型 非用车
        $map['orderType'] = ['in',['Ticket_FIT','Ticket_POI','Hotel','Ticket_AIR']];
        //是否拼团产品 拼团不显示
        $map['is_group']='0';

        $totalNum = $m->where($city_function)->where($map)->count('city_id');
        //总页数
        $start = ($page-1)*$offset;

        $data= db("goods")->where($city_function)
            ->where($map)
            ->field('goods_id as id,goods_name as name,goods_tcode,
            goods_image,small_image as img ,classify_id,price,orderType,
            goods_englishname as eng_name,starttime,endtime,recommend,popular,
            updating,goodstag_id,goodssales,invented_sold,show,price_section,standard_pro,
            channel_source,source_id,merchantCancellable')
//            ->order('updating desc')
            ->order('goods_id desc,updatetime desc')
            ->select();
        if(empty($data)){
            return $result;
        }
        //获取viator的折扣
        $discoun_num = 1;//默认没有折扣
        $discoun_viator=Db::name('viator_discount')
            ->field('discount_num')
            ->where(['id'=>1,'status'=>1])
            ->find();
        if(!empty($discoun_viator)){
            $discoun_num = $discoun_viator['discount_num']??1;
        }

        foreach ($data as $k=>$v){
            if(!empty($v['price'])){
                //viator 商品折扣计算
                if($v['show'] == 2 && !empty($discoun_num)){
                    $v['price']= $v['price'] * $discoun_num;
                }

                $oldPrice = $v['price'];
                $salePrice = ceil($v['price']*$exchange['exchange_rate']);
            }else{
                //产品价格替换
                $product_id = '';
                $product_price_exists = 0;//是否存在产品价格
                //存在产品时
                if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
                    $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();
                    if(!empty($product) && $product['base_price_mode']==1) {
                        $product_id = $product['id'];
                        $product_price_exists = 2;//存在产品设置基础价格
                    }elseif(!empty($product) && $product['new_price_flag']==1){
                        $product_id = $product['id'];
                        $product_price_exists = 1;//存在产品设置价格
                    }
                }

                if($product_price_exists==2){
                    $dayPrice = db('product_base_dailyprice p')
                        ->where(['product_id'=>$product_id])
                        ->field('p.price as person_price')
                        ->select();
                    //关联产品的价格问题
                    if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                        //默认人民币汇率
                        if(!empty($exchangeRate['exchange_rate'])){
                            foreach ($dayPrice as $key=>$value){
                                $dayPrice[$key]['person_price'] = ceil(round($value['person_price'])*$exchangeRate['exchange_rate']);
                            }
                        }
                    }

                }elseif($product_price_exists==1){
                    $dayPrice = db('product_dailyprice p')
                        ->where(['product_id'=>$product_id])
                        ->field('p.price as person_price')
                        ->select();
                }else{
                    $dayPrice = db('personday p')
                        ->where(['goods_id'=>$v['id']])
                        ->field('p.person_price')
                        ->select();
                }

                if (!empty($dayPrice)){
                    $price = array_column($dayPrice,'person_price');
                    $max = max($price);
                    $min = min($price);

                    //viator 商品折扣判断
                    if($v['show'] == 2 && !empty($discoun_num)){
                        $max = ceil($discoun_num * $max);
                        $min = ceil($discoun_num * $min);
                    }
                    $oldPrice='';
                    $salePrice=  $min.'~'.$max;
                    if ($max==$min || $min=='0'){
                        $salePrice=ceil($max);
                    }

                }elseif($v['channel_source']=='fareharbor'){
                    // fareharbor商品价格
                    $oldPrice = '';
                    $salePrice = $v['price_section'];
                }
            }
            //获取图片地址
            $image_arr = empty($v['img'])?$v['goods_image']:$v['img'];
            $image = explode(',',$image_arr);
            $image = array_values(array_filter($image));
            $image = $image[0]??'';
            //获取最早售卖日期
            if (time()>$v['starttime'] && time()<$v['endtime'] ){
                $zuizao = '今天';
            }else if(time()<$v['starttime']){
                $zuizao = date('m-d',$v['starttime']);
            }else{
                $zuizao='未知';
            }
            //商品分类
            //追加类型返回
            $classify_name=Db::name('classify')->where(['classify_id'=>$v['classify_id']])->find();
            $classify_name=empty($classify_name)?'':$classify_name['classify_name'];

            //追加商品标签
            $goodstag = Db::name('goodstag')->where(['tag_id'=>$v['goodstag_id'],'tag_status'=>1])->field('tag_name')->find();
            $goodstag=empty($goodstag)?'':$goodstag['tag_name'];

            //评论数
            $where_comment['goods_id'] = $v['id'];
            $comment_num = Db::name("comment")->where($where_comment)->count("comment_id");

            if (!empty($salePrice) || !empty($oldPrice)){
                $d['goods'][]=[
                    'goods_id'=>$v['id'],
                    'orderType'=>$v['orderType'],
                    'recommend'=>$v['recommend'],
                    'popular'=>$v['popular'],
                    'name'=>$v['name'],
                    'jiage'=>$salePrice,
                    'image'=>$image,
                    'eng_name'=>$v['eng_name'],
                    'zuizao'=>$zuizao,
                    'yuanjia'=>$oldPrice,
                    'updating'=>$v['updating'],
                    'comment_num'=>$comment_num,
                    'order_num'=>$v['goodssales'] + $v['invented_sold'],
                    'ifytype'=>$classify_name,  //水印内容
                    'goodstag'=>$goodstag,   //商品标签
                    'merchantCancellable'=>$from=='toB'?1:$v['merchantCancellable'],//是否可退
                ];
            }
        }

        if (in_array($sort,['1','2'])){
            $d = (new WapGoodsController())->insertSort($d,$sort);
        }

        $list = array_slice($d['goods'],$start,$offset);
        return [$totalNum,$list];
    }

    //配置车型对象
    public function getCarInfo($carType)
    {
        if(empty($carType)) return [];
        $carInfo['carTypeTitle'] = $this->getCarTypeTitle($carType);
        switch ($carType){
            case 1:
                $maxPersonNum = 3;
                $maxBaggageNum = 3;
                break;
            case 10:
                $maxPersonNum = 6;
                $maxBaggageNum = 6;
                break;
            case 20:
                $maxPersonNum = 11;
                $maxBaggageNum = 11;
                break;
            default :
                $maxPersonNum = 0;
                $maxBaggageNum = 0;
                break;
        }
        $carInfo['maxPersonNum'] =$maxPersonNum;
        $carInfo['maxBaggageNum'] = $maxBaggageNum;

        return $carInfo;
    }
    //获取商品详情
    public function getGoodsInfo($standard_id,$from='toB')
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'标品暂未上架'];
        }
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;
        //获取商品折扣
        if($from=='toB'){
            $discount_rate = $this->getDiscountRatePriceToB($standard_id);
        }else{
            $discount_rate = 1;
        }

        $typesource = "myself";
        //获取标签
        $tag_id=explode(',',$goods['tag_id']);
        $tags = db('tag')
            ->field("tag_id,tag_name")
            ->where(['tag_id'=>['in',$tag_id]])
            ->select();
        //折扣价和原价【价格区间】
        $discount_price = '';
        $old_price = '';
        $ageBands = [];
        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //存在viator价格
        if($goods['show'] == 2){
            if(!empty($discount_rate)){
                $typesource = "viator";
                $old_price = $goods['price'];
                $discount_price = $old_price*$discount_rate;
                $ageBands = cache($goods['third_code'].'ageBands');
            }

            $old_price = ceil($old_price*$local_exchange);
            $old_price = strval($old_price);
            $discount_price = ceil($discount_price*$local_exchange);
            $discount_price = strval($discount_price);
        }elseif($goods['standard_pro']==1 && $goods['channel_source']=='fareharbor'){
            //折扣价为美元价
            $typesource = 'fareharbor';
            //获取farehabor利润点
            $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
            $sell_percent_rate = empty($sell_rate)&&$sell_rate['discount_num']?1:$sell_rate['discount_num'];
            if(!empty($goods['source_id'])){
                $usd_price_section = db('fareharbor_goods')->field('usd_price_section')->find($goods['source_id'])['usd_price_section']??0;
                $usd_price_section = explode('~',$usd_price_section);
                $fare_price = $usd_price_section[0]??0;
            }
            $old_price = !empty($fare_price)?ceil($fare_price*$local_exchange*$sell_percent_rate):ceil($goods['price_section']);
            $discount_price = !empty($fare_price)?ceil($fare_price*$local_exchange*$sell_percent_rate*$discount_rate):ceil($old_price*$discount_rate);
            $old_price = strval($old_price);
            $discount_price = strval($discount_price);
        }else{
            list($discount_price,$old_price) = $this->getPriceSectionByGoods($goods,$discount_rate);
            if(empty($discount_price)) return ['code'=>400,'msg'=>'商品不可售'];
        }
        //商品推荐 同城售卖商品【排除此商品】
        $GModel = new G();
        $sql  = "select goods_id,goods_name,price_section,goods_image,`show`,price,city_id from tplay_goods as g ";
        $sql .= ' join (select round(rand() * (select max(goods_id) from tplay_goods)) as id) as t ';
        $sql .= ' where g.goods_id >=t.id and city_id= '.$goods["city_id"].' and goods_id!='.$goods_id.' and goods_status=1';
        $sql .= ' order by g.goods_id  asc limit 4';
        $recommendProList = $GModel->query($sql);
        if(empty($recommendProList)){
            $recommendProList = $GModel->query($sql);
        }

        //推荐数据集合
        $recList = [];
        foreach ($recommendProList as $rec_key=>$rec_value){
            $rec_old_price='';
            if(!empty($rec_value['price'])){
                $rec_discount_price = ceil($rec_value['price']*$local_exchange);
                $rec_old_price = $rec_discount_price = strval($rec_discount_price);
            }else{
                list($rec_discount_price,$rec_old_price) = $this->getPriceSectionByGoods($rec_value,$discount_rate);
            }
            $image = array_values(array_filter(explode(",",$goods['goods_image'])))??[];
            if(!empty($image)){
                foreach ($image as $image_k=>$image_v){
                    $image[$image_k] = $this->checkImgUrl($image_v);
                }
            }
            $recList[] = [
                'goods_id'=>$rec_value['goods_id'],
                'goods_name'=>$rec_value['goods_name'],
                'price_section'=>$rec_discount_price,
                'old_price_section'=>$rec_old_price,
                'image'=>$image,
                'img_type'=>$rec_value['show'],
            ];
        }
        //商品评论 数量3
        $comment =db('comment')
            ->alias('a')
            ->join('member d','a.member_id=d.member_id')
            ->join('attachment b','b.id=d.thumb')
            ->where('a.goods_id',$goods_id)
            ->where('a.comment_status',2)
            ->field('a.content,a.creattime,a.comment_img')
            ->field('a.content,a.creattime,d.member_nickname,b.filepath as touxiang,a.comment_img')
            ->order('a.creattime desc')
            ->limit(3)
            ->select();
        $commentList=[];
        if (!empty($comment)){
            foreach ($comment as $c){
                $commentImg = empty($c['comment_img'])?"":json_decode($c['comment_img']);
                $commentList[]= [
                    'content'=>$c['content'],
                    'creattime'=>date('Y-m-d H:i:s',$c['creattime']),
                    'member_nickname'=>$c['member_nickname'],
                    'touxiang'=>$c['touxiang'],
                    'img'=>$commentImg
                ];
            }
        }
        //获取总评论数
        $comment_num = db("comment")->where(['goods_id'=>$goods_id])->count();
        //获取图片列表
        $goodsImgArr = array_values(array_filter(explode(",",$goods['goods_image'])));
        if(!empty($goodsImgArr)){
            foreach ($goodsImgArr as $img_key=>$img_value){
                if(false === strpos($img_value,'http')) $goodsImgArr[$img_key] = config('image_source').$img_value;
            }
        }
        $UntreatedImgArr = $goodsImgArr;
        $goodsImgArr = $this->batchOssImgUrl($goodsImgArr);
        $video_img = $goodsImgArr[0]??"";
        //视频处理
        $video = ['src'=>$goods['goods_video'],'img'=>''];
        //最早可购买时间
        $startDay='未知';
        if (time()>$goods['starttime'] && time()<$goods['endtime'] ){
            $startDay = '今天';
        }elseif(time()<$goods['starttime']){
            $startDay = date('Y-m-d',$goods['starttime']);
        }
        $toursLineTitle = '';
        $isTextPlan = false;
        $textPlan = '';
        $service_language = 'cn';
        $customer_content = [];
        $featuredProduct = new \ArrayObject();
        $activityInfo = new \ArrayObject();
        $selfDriveInfo = new \ArrayObject();
        $virtualInfo= new \ArrayObject();
        //行程线路
        $standardtrip = db('standardtrip')->where('sid',$standard_id)->find();
        if(!empty($standardtrip)){
            $toursLineTitle = $standardtrip['toursLineTitle']??'';
            if(!empty($standardtrip['trip_id'])){
                $productInfo = db('product')->field('service_language,customer_content,
                    net_weight,shelf_life,production_date,production_license,storage_conditions,edible_methods,executive_standard_no,
                    assembling_place,activity_duration,activity_person_num,play_ways,
                    self_driving_level,vehicle_require,itinerary_summary,self_driving_distance,
                    is_text_plan,text_plan,customer_info_config,all_customer_req')->where('id',$standardtrip['trip_id'])->find();
                $service_language = $productInfo['service_language']==1?'en':$service_language;
                $customer_content = !empty($productInfo['customer_content'])?json_decode($productInfo['customer_content'],true):[];
                $isTextPlan = !empty($productInfo['is_text_plan'])?true:false;
                $textPlan = !empty($productInfo['text_plan'])? $this->replaceUeditorImgUrl($productInfo['text_plan']) : '';
                if(!empty($goods['orderType']) && $goods['orderType']=='FeaturedProduct'){
                    $featuredProduct = [
                        'net_weight'=>$productInfo['net_weight'],
                        'shelf_life'=>$productInfo['shelf_life'],
                        'production_date'=>$productInfo['production_date'],
                        'production_license'=>$productInfo['production_license'],
                        'storage_conditions'=>$productInfo['storage_conditions'],
                        'edible_methods'=>$productInfo['edible_methods'],
                        'executive_standard_no'=>$productInfo['executive_standard_no'],
                    ];
                }elseif (!empty($goods['orderType']) && $goods['orderType']=='StdActivity'){
                    $activityInfo = [
                        'assembling_place'=>$productInfo['assembling_place'],
                        'activity_duration'=>$productInfo['activity_duration'],
                        'activity_person_num'=>$productInfo['activity_person_num'],
                        'play_ways'=>$productInfo['play_ways']
                    ];
                }elseif (!empty($goods['orderType']) && $goods['orderType']=='StdSelfDrive'){
                    $selfDriveInfo = [
                        'assembling_place'=>$productInfo['assembling_place'],
                        'self_driving_level'=>$productInfo['self_driving_level'],
                        'vehicle_require'=>$productInfo['vehicle_require'],
                        'itinerary_summary'=>$productInfo['itinerary_summary'],
                        'self_driving_distance'=>$productInfo['self_driving_distance'],
                    ];
                }elseif (!empty($goods['orderType']) && $goods['orderType']=='VirtualProduct'){
                    $virtualInfo = db('product_electronic')
                        ->field("electronic_supplier,electronic_tpl_id,electronic_source,
                            electronic_validate,electronic_cost_price,electronic_refer_price,electronic_scenic_spots,
                            electronic_poi_name,electronic_scenic_latlng")
                        ->where(['electronic_pro_id'=>$standardtrip['trip_id']])->find();
                    if(empty($virtualInfo)){
                        $virtualInfo = new \ArrayObject();
                    }else{
                        $virtualInfo['electronic_scenic_latlng'] = !empty($virtualInfo['electronic_scenic_latlng']) ?
                            json_decode($virtualInfo['electronic_scenic_latlng'],true) :
                            new \ArrayObject();
                    }
                }
            }
        }
        $foreign_old_price = "";
        if(!empty($old_price)){
            $old_price_arr = explode("~",$old_price);
            if(count($old_price_arr)>1){
                $f_min = ceil(($old_price_arr[0]/$local_exchange));
                $f_max = ceil(($old_price_arr[1]/$local_exchange));
                $foreign_old_price = $f_min.'~'.$f_max;
            }elseif(!empty($old_price_arr[0])){
                $foreign_old_price = ceil(($old_price_arr[0]/$local_exchange));
            }
        }
        $foreign_discount_price = "";
        if(!empty($discount_price)){
            $discount_price_arr = explode("~",$discount_price);
            if(count($discount_price_arr)>1){
                $f_min = ceil(($discount_price_arr[0]/$local_exchange));
                $f_max = ceil(($discount_price_arr[1]/$local_exchange));
                $foreign_discount_price= $f_min.'~'.$f_max;
            }elseif(!empty($discount_price_arr[0])){
                $foreign_discount_price = ceil(($discount_price_arr[0]/$local_exchange));
                $foreign_discount_price = strval($foreign_discount_price);
            }
        }
        $standard_type = $standard['type']??"";
        $standard_type_name = $this->getTypeName($standard_type);
        $data = [
            'standard_id'=>$standard_id,//标品id
            'standard_type'=>$standard_type,//标品类型
            'standard_type_name'=>$standard_type_name,//标品类型名称
            'goods_id'=>$goods['goods_id'],//商品id
            'title'=>$standard['name']??$goods['goods_name'],//商品中文名
            'eng_name'=>$goods['goods_englishname'],//商品英文名
            'subTitle'=>$standard['introduce']??'',//副标题
            'introduction'=>$standard['introduce']??'',//副标题
            'orderType'=>$goods['orderType'],//商品订单类型
            'viator_code'=>$goods['third_code'],
            'product_code'=>$goods['goods_tcode'],
            'typesource'=>$typesource,//商品类型
            'collection'=>0,//是否收藏
            'zuizao'=>$startDay,//最早可购买时间
            'Sales'=>$goods['goodssales'] + $goods['invented_sold'],// 商品销量
            'comment_num'=>$comment_num,//评论数
            'comment'=>$commentList,//评论
            'tags'=>$tags,//tag标签
            'discount_rate'=>$discount_rate,//折扣
            'discount_price'=>$discount_price,//商品会员折扣价
            'old_price'=>$old_price,//商品原价
            'img'=>['image'=>$goodsImgArr,'UntreatedImg'=>$UntreatedImgArr,'video'=>$video],//商品视频 轮播图
            'recList'=>$recList,//猜你喜欢 推荐
            'goods_introduce'=>$isTextPlan?$textPlan:$this->replaceUeditorImgUrl($goods['goods_introduce']),//产品介绍
            'price_include'=>$goods['price_include'],//费用包含
            'price_noinclude'=>$goods['price_noinclude'],//费用不含
            'goods_careful'=>$goods['goods_careful'],//注意事项
            'goods_retreating'=>$goods['goods_retreating'],//退改规则
            'fromCityId'=>$goods['city_id'],//城市id
            'fromCityName'=>$goods['city_name'],//城市名称
            'fromCityKbxId'=>$goods['kbx_city_id'],//城市名称
            'goods_status'=>$goods['goods_status'],//城市名称
            'need_confirm'=>!empty($goods['need_confirm']) && $goods['need_confirm']==1?true:false,//是否需要二次确认
            'currency'=>$currency_code,//外币类型
            'foreign_discount_price'=>$foreign_discount_price,//外币    商品会员折扣价
            'foreign_old_price'=>$foreign_old_price,//外币    商品原价
            'ageBands'=>$ageBands,//viator套餐
            'merchantCancellable'=>$from=='toB'?1:$goods['merchantCancellable'],//是否可退
            'toursLineTitle'=>$toursLineTitle,//行程线路
            'service_language'=>$service_language,//服务语言
            'customer_content'=>$customer_content,//更多条款
            'FeaturedProduct'=>$featuredProduct,
            'activityInfo'=>$activityInfo,
            'selfDriveInfo'=>$selfDriveInfo,
            'virtualInfo'=>$virtualInfo,
            'isTextPlan'=>$isTextPlan,
            'isGroupExhibition'=>!empty($standard['is_group_exhibition'])
                 && empty($standard['allow_everyone_quote']) ? true : false,
            'likeCount'=>$standard['like_count'] ?? 0,
        ];
        $data['allCustomerInfoReq'] = !empty($productInfo['all_customer_req'])?true:false;
        $customer_info_config = $productInfo['customer_info_config']??'';
        $data['customerInfoConfig'] = $this->getProductCustomerInfoConfig($customer_info_config);
        //是否为viator商品
        if($goods['show']==2){
            //进行验证
            $code = $goods['third_code'];
            $viator = new Viator();
            $res = $viator->checkGoods($code);
            if($res['code']==1){//code=1时为验证失败
                return $res['data'];
            }else{
                $goods_res = $res['data'];//验证时取的新数据
                if(!empty($goods_res['bookingQuestions'])){
                    $data['bookingQuestions'] = $goods_res['bookingQuestions'];//增加预约问题数据
                }
                //价格为空 则尝试获取接口价格
                if(empty($data['discount_price'])){
                    $data['viatorData'] = $goods_res;
                    list($data['discount_price'],$data['old_price']) = $this->getViatorApiPrice($goods_res,$discount_rate);
                }
            }
        }
        //是否属于供应商 商品关联的产品是否有supplier_admin_id
        $data['productId'] = $data['supplierId'] = $data['introduction'] = '';
        if(!empty($data['product_code'])){
            $productInfo = db('product')->field('id,supplier_admin_id,introduction')->where('item_num',$data['product_code'])->find();
            if(!empty($productInfo['supplier_admin_id'])){
                $data['supplierId'] = db('supplier_admin')->find($productInfo['supplier_admin_id'])['company_id']??'';
            }
            $data['introduction'] = $productInfo['introduction']??'';
            $data['productId'] = $productInfo['id']??'';
        }
        //增加产品类型
        $data['classificationTags'] = $this->getStandardTags($standard_id);

        return $data;
    }

    //产品配置的出行人信息
    public function getProductCustomerInfoConfig($customer_info_config)
    {
        $masterCustomer = $secondCustomer = [];
        $customer_info_config = !empty($customer_info_config) ?
            explode(',',$customer_info_config) :
            $this->customerAttrs;
        foreach ($customer_info_config as $value){
            $data = explode('-',$value);
            if(!empty($data[3])){
                $masterCustomer[] = [
                    'name'=>$data[0]??'',
                    'key'=>$data[1]??'',
                    'isRequired'=>!empty($data[4]),
                ];
                $secondCustomer[] = [
                    'name'=>$data[0]??'',
                    'key'=>$data[1]??'',
                    'isRequired'=>!empty($data[5]),
                ];
            }

        }
        $result['masterCustomer'] = $masterCustomer;
        $result['secondCustomer'] = $secondCustomer;
        return $result;
    }
    //获取价格区间
    public function getPriceSectionByGoods($goods,$viator_discount,$noRate=false)
    {
        $goodsCode = db("goods")->where("goods_id",$goods['goods_id'])->field("goods_tcode")->find();
        //产品价格替换
        $product_id = '';
        $product_section = '';
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goodsCode['goods_tcode']) && $goodsCode['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goodsCode['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();
            if(!empty($product) && $product['base_price_mode']==1){
                $product_id = $product['id'];
                $product_section = $product['price_section'];
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_id = $product['id'];
                $product_section = $product['price_section'];
                $product_price_exists = 1;//存在产品设置价格
            }
        }

        if($product_price_exists==2){
            $price_section = explode("~",$product_section);
            $old_min = $min = $price_section[0]??0;
            $old_max = $max = $price_section[1]??$min;

//            $min = ceil($min*$viator_discount);
//            $max = ceil($max*$viator_discount);
//            $product_cost = db("product_base_dailyprice pd")
//                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
//                ->field("min(pd.total_cost*pd.minorder_num*100/(100-ps.bdj_rate)) as minprice,max(pd.total_cost*pd.minorder_num*100/(100-ps.bdj_rate)) as maxprice")
//                ->where(['product_id'=>$product_id,'total_cost'=>['gt',0],'ps.special'=>['lt',1]])
//                ->find();
            $product_sale_price = db("product_base_dailyprice pd")
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->field("min(pd.price) as minprice,max(pd.price) as maxprice")
                ->where(['product_id'=>$product_id,'price'=>['gt',0],'ps.special'=>['lt',1]])
                ->find();
            $min = round($product_sale_price['minprice']??0);
            $max = round($product_sale_price['maxprice']??0);
            //关联产品的价格问题
            if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                $local_exchange = $exchangeRate['exchange_rate']??1;//默认人民币汇率
                $min = ceil($min*$local_exchange);
                $max = ceil($max*$local_exchange);
                $old_min = ceil($old_min*$local_exchange);
                $old_max = ceil($old_max*$local_exchange);
            }
        }elseif($product_price_exists==1){
            $price_section = explode("~",$product_section);
            $old_min = $min = $price_section[0]??0;
            $old_max = $max = $price_section[1]??$min;
            $min = ceil($min*$viator_discount);
            $max = ceil($max*$viator_discount);
        }else{
            if(empty($goods['price_section'])){
                $specsprice = db('personday')->alias('p')
                    ->where('p.goods_id', $goods['goods_id'])
                    ->field('p.person_price')
                    ->select();
                if(!empty($specsprice)){
                    $person_price = array_column($specsprice,'person_price');
                    $old_max = $max = max($person_price);
                    $old_min = $min = min($person_price);
                    $max = ceil($max*$viator_discount);
                    $min = ceil($min*$viator_discount);
                }else{
                    $old_max = $max = $old_min = $min = 0;
                }
            }else{
                $price_section = explode("~",$goods['price_section']);
                $old_min = $min = $price_section[0]??0;
                $old_max = $max = $price_section[1]??$min;
                $min = ceil($min*$viator_discount);
                $max = ceil($max*$viator_discount);
            }
        }

        if($max!=$min){
            $old_price = $old_min.'~'.$old_max;
            $discount_price = $min.'~'.$max;
        }else{
            $old_price = strval($old_min);
            $discount_price = strval($min);
        }
        return [$discount_price,$old_price];
    }

    //获取商品套餐日历价格
    public function getGoodsSpec($standard_id,$noRate=false)
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'标品暂未上架'];
        }
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;
        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //获取折扣
        $discount_rate = $this->getDiscountRatePriceToB($standard_id);
        //检查商品类型
        if(!empty($goods['standard_pro']) && $goods['channel_source']=='fareharbor'){
            //获取farehabor利润点
            $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
            $sell_percent_rate = empty($sell_rate)&&$sell_rate['discount_num']?1:$sell_rate['discount_num'];
            $faregoods = db("fareharbor_goods")->find($goods['source_id']);
            if(empty($faregoods)) return ['code'=>400,'msg'=>'商品未上架'];

            $company = $faregoods['company'];
            $item = $faregoods['item_id'];
            $specs = (new F())->getItemSpecsList($company,$item);
            if(!empty($specs)){
                foreach ($specs as $key=>$value){
                    $specs[$key]['min_price'] = ceil($value['min_price']*$local_exchange*$discount_rate*$sell_percent_rate);
                }
            }
            return [
                'specs'=>$specs,
                'goods_id'=>$item,
                'discount_rate'=>$discount_rate,
                'typesource'=>'fareharbor',
            ];
        }

        //Viator商品
        if(!empty($goods['third_code']) && $goods['show']== 2){
            $data= cache($goods['third_code'].'price');
            if(empty($data)){
                $data['specs'] = [];
            }else{
                array_pop($data);
                $d = [];
                foreach ($data as $s=>$value){
                    foreach ($value as $k=>$v) {
                        $viator_price = [];
                        foreach ($v['ageBands'] as $k_a=>$v_a) {
                            $data[$s][$k]['ageBands'][$k_a]['merchantNetPrice'] = isset($v_a['merchantNetPrice'])?strval($v_a['merchantNetPrice']):"";
                            if($v_a['price']>0){
                                $viator_price[] = strval(ceil($v_a['price']*$local_exchange*$discount_rate));
                            }
                        }

                        $min_price = min($viator_price);
                        $d[$v['bookingDate']][] = ['shijian'=>$v['bookingDate'],'min_price'=>$min_price];
                    }
                }
                foreach ($d as $key=>$value){
                    $dateArr = [];
                    $dateArr['number'] = 999;
                    $dateArr['time'] = $key;
                    $jiaGe = array_column($value,'min_price');
                    $dateArr['min_price'] = min($jiaGe);
                    $result['specs'][]=$dateArr;
                }
            }
            $result['goods_id']   = $goods_id;
            $result['typesource'] ='viator';
            $result['discount_rate'] = $discount_rate;
            return $result;
        }

        //产品价格替换
        $product_id = '';
        $product_section = '';
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();
            if(!empty($product) && $product['base_price_mode']==1){
                $product_id = $product['id'];
                $product_section = $product['price_section'];
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_id = $product['id'];
                $product_section = $product['price_section'];
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        //获取可售卖的时间 截止天数+当前时间
        //地接社类标品
        if(!empty($standard['s_endDays'])){
            $sale_time = $standard['s_endDays']==1?strtotime('+1 day'):strtotime('+'.$standard['s_endDays'].' days');
        }else{
            $standardtrip = db('standardtrip')->where('sid',$standard_id)->find();
            if(!empty($standardtrip['endDays']) && $standardtrip['endDays']>0){
                $sale_time = $standardtrip['endDays']==1?strtotime('+1 day'):strtotime('+'.$standardtrip['endDays'].' days');
            }else{
                $sale_time = time();
            }
        }
        $sale_time = date('Y-m-d',$sale_time);
        if($product_price_exists==2){
            //获取所有的日期的价格设置
            $personday = db('product_base_dailyprice pd')
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->where(['pd.product_id'=>$product_id,'pd.time'=>['egt',$sale_time]])
                ->field("pd.*,pd.name as person_name,pd.total_cost*100/(100-ps.bdj_rate) as person_price,pd.num as person_num,pd.package_id as specs_id,pd.specs_id as person_id")
                ->order("pd.time asc")
                ->select();
            //关联产品的价格问题
            if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                //默认人民币汇率
                if(!empty($exchangeRate['exchange_rate'])){
                    foreach ($personday as $key=>$value){
                        $personday[$key]['person_price'] = ceil(round($value['person_price'])*$exchangeRate['exchange_rate']);
                        $personday[$key]['price'] = ceil(round($value['price'])*$exchangeRate['exchange_rate']);
                    }
                }
            }
        }elseif($product_price_exists==1){
            //获取所有的日期的价格设置
            $personday = db('product_dailyprice')
                ->where(['product_id'=>$product_id,'time'=>['egt',$sale_time]])
                ->field("*,name as person_name,price as person_price,num as person_num,package_id as specs_id,specs_id as person_id")
                ->order("time asc")
                ->select();
        }else{
            //获取所有的日期的价格设置
            $personday = db('personday')
                ->where(['goods_id'=>$goods_id,'time'=>['egt',$sale_time]])
                ->order("time asc")
                ->select();
        }
        if(empty($personday)) return ['code'=>400,'msg'=>'暂未配置价格'];

        $days = array_values(array_unique(array_column($personday,"time")));
        foreach ($days as $day_key=>$day_value){
            $days[$day_key] = [];
            foreach ($personday as $p_k=>$p_v){
                if($p_v['time']==$day_value){
                    $days[$day_key]['time'] = $day_value;
                    $days[$day_key]['specs'][] = $p_v;
                }
            }
        }
        if(empty($days)) return ['code'=>400,'msg'=>'暂未配置价格'];
        foreach ($days as $day_key=>$day_value){
            $saleNum = [];
            $price = [];
            foreach ($day_value['specs'] as $specs){
                $saleNum[] = $specs['person_num'];
                $price[] = $product_price_exists==2?round($specs['person_price']):ceil($specs['person_price']*$discount_rate);
            }
            $min_price = 0;
            $min_salenum = 0;
            if(!empty($price)){
                $min_price = min($price);
                $min_key = array_search($min_price,$price);
                $min_salenum = $saleNum[$min_key];
            }
            $days[$day_key]['min_price'] = $min_price;
            $days[$day_key]['min_salenum'] = $min_salenum;
            unset($days[$day_key]['specs']);
        }
        $data['specs'] = $days;
        $data['goods_id'] = $goods_id;
        $data['discount_rate'] = $discount_rate;
        $data['type'] = 'myself';
        $data['sale_time'] = $sale_time;
        return $data;
    }

    //获取套餐详情
    public function getGoodsSpecInfo($standard_id,$time,$noRate=false)
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'标品暂未上架'];
        }
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;
        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //获取折扣
        $discount_rate = $this->getDiscountRatePriceToB($standard_id);

        if(!empty($goods['third_code']) && $goods['show']==2){
            $data = cache($goods['third_code'].'price');
            //By Suley
            //修改过的自定义套餐名称
            $where_name['code'] = $goods['third_code'];
            $specsName = db('specsname')->where($where_name)->select();
            $nameArr = array();
            if(!empty($specsName)){
                foreach ($specsName as $k_name=>$v_name){
                    $nameArr[$v_name['grade_code']] = $v_name['new_name'];
                }
            }

            $eto_list=[
                'Adult'   => '成人',
                'Child'   => '儿童',
                'Infant'  => '婴儿',
                'Youth'   => '青年',
                'Senior'  => '老年人',
                '成年人'  => '成年人',
                '儿童'    => '儿童',
                '婴儿'    => '婴儿'
            ];


            $d=[];
            if(!empty($data)){
                unset($data['month_num']);
                foreach ($data as $s=>$v){
                    foreach ($v as $key_grade=>$value_grade) {
                        if ($value_grade['bookingDate']==$time){
                            foreach ($value_grade['ageBands'] as $l=>$k){
                                $data[$s][$key_grade][$l]['merchantNetPrice'] = strval($k['merchantNetPrice']);
                                $person_price= ceil($local_exchange*$k['price']*$discount_rate);
                                $person_price = strval($person_price);

                                $description_name = isset($eto_list[$k['description']]) ? $eto_list[$k['description']] : $k['description'];
                                if(isset($nameArr[$s])){
                                    $grade_name = $nameArr[$s];
                                }else{
                                    if($s=='DEFAULT'){
                                        $grade_name = "普通套餐";
                                    }else{
                                        $grade_name = $s;
                                        $goods_type = cache($goods['third_code'].'type');
                                        foreach ($goods_type as $t_key=>$t_value) {
                                            if($s==$t_value['gradeCode']){
                                                $grade_name = !empty($t_value['specs_name'])?$t_value['specs_name']:$t_value['specs_ename'];
                                            }
                                        }
                                        //为解决Viator商品的套餐名字段更新问题，自动对比增加
                                        $new_grade_code_Arr = explode("~",$s);
                                        $new_s = !empty($new_grade_code_Arr[0]) ? $new_grade_code_Arr[0] : '';
                                        if($new_s!==''){
                                            if(isset($nameArr[$new_s])){
                                                foreach ($goods_type as $t_key=>$t_value) {
                                                    if($s==$t_value['gradeCode']){
                                                        $grade_name = $nameArr[$new_s];
                                                        $new_specs_name = $t_value['specs_name'];
                                                        $p_data = array();
                                                        $p_data['code'] = $goods['third_code'];
                                                        $p_data['grade_code'] = $s;
                                                        $p_data['specs_name'] = $new_specs_name;
                                                        $p_data['new_name'] = $grade_name;

                                                        //防止重复插入
                                                        $p_specsname = db("specsname")->where("grade_code",$s)->find();
                                                        if(empty($p_specsname)){
                                                            db("specsname")->insert($p_data);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                $d[$grade_name][]=[
                                    "person_id"=>$k['bandId'],
                                    "gradeCode"=>$s,
                                    "person_price"=>$person_price,
                                    "person_num"=>999,
                                    "inc_order_num"=>1,
                                    "person_name"=>$k['age'].'岁'.$description_name,
                                    "max"=>$k['max'],
                                    "min"=>$k['min'],
                                ];
                            }
                            break;
                        }
                    }
                }
            }
            $specsList = [];
            foreach ($d as $k=>$v) {
                $a['specs_id'] = '9999999999';
                $a['specs_name'] = $k;
                $a['person'] = $v;
                $a['ageBands'] = $value_grade['ageBands'];
                $a['gradeCode'] = $v[0]['gradeCode'];
                $specsList[] = $a;
            }

            $result['typesource'] = 'viator';
            $result['specs'] = $specsList;
            return $result;
        }
        //检查fareharbor类型
        if(!empty($goods['standard_pro']) && $goods['channel_source']=='fareharbor'){
            $faregoods = db("fareharbor_goods")->find($goods['source_id']);
            if(empty($faregoods)) return ['code'=>400,'msg'=>'暂未配置套餐价格'];
            $company = $faregoods['company'];
            $item = $faregoods['item_id'];
            $date = $time;
            $specs = (new F())->specsOneItem($company,$item,$date,$discount_rate);
            $specsName = db('faregoods_specname')->where('item_id',$item)->select();
            if(!empty($specsName)){
                $specsEnName = array_column($specsName,'en_name');
            }else{
                $specsEnName = [];
            }
            //翻译名称
            foreach ($specs as $i=>$s){
                foreach ($s['person'] as $x=>$p){
                    if(array_search($p['person_name'],$specsEnName)!==false){
                        $cn_name = $specsName[array_search($p['person_name'],$specsEnName)]['ch_name'];
                    }else{
                        $cn_name = $p['person_name'];
                    }
                    $specs[$i]['person'][$x]['person_name'] = $cn_name;
                }
            }
            $data = [
                'specs'=>$specs,
                'typesource'=>'fareharbor'
            ];
            return $data;
        }

        $where = [];
        $where['goods_id']  = $goods_id;
        $where['time']      = $time;

        //产品价格替换
        $product_id = '';
        $product_section = '';
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();
            if(!empty($product) && $product['base_price_mode']==1) {
                $product_id = $product['id'];
                $product_section = $product['price_section'];
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_id = $product['id'];
                $product_section = $product['price_section'];
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        if($product_price_exists==2){
            $where_p['pd.product_id']  = $product_id;
            $where_p['pd.time']        = $time;
            //获取规格
            $personday = db('product_base_dailyprice pd')
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->where($where_p)
                ->field('pd.*,pd.name as person_name,pd.total_cost*100/(100-ps.bdj_rate) as person_price,pd.num as person_num,pd.package_id as specs_id,pd.specs_id as person_id')
                ->order('pd.time asc,pd.specs_id asc')
                ->select();
            //关联产品的价格问题
            if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                //默认人民币汇率
                if(!empty($exchangeRate['exchange_rate'])){
                    foreach ($personday as $key=>$value){
                        $personday[$key]['person_price'] = ceil(round($value['person_price'])*$exchangeRate['exchange_rate']);
                        $personday[$key]['price'] = ceil(round($value['price'])*$exchangeRate['exchange_rate']);
                    }
                }
            }
            //获取套餐
            $specs = db('product_base_package')
                ->where(['product_id'=>$product_id])
                ->where('status',1)
                ->field('id as specs_id,name as specs_name')
                ->select();
        }elseif($product_price_exists==1){
            $where_p['product_id']  = $product_id;
            $where_p['time']        = $time;
            //获取规格
            $personday = db('product_dailyprice')
                ->where($where_p)
                ->field('*,name as person_name,price as person_price,num as person_num,package_id as specs_id,specs_id as person_id')
                ->order('time asc,person_id asc')
                ->select();
            //获取套餐
            $specs = db('product_package')
                ->where(['product_id'=>$product_id])
                ->where('status',1)
                ->field('id as specs_id,name as specs_name')
                ->select();
        }else{
            //获取规格
            $personday =  db('personday')
                ->where($where)
                ->order('time asc,person_id asc')
                ->select();
            //获取套餐
            $specs = db('specs')
                ->where(['goods_id'=>$goods_id])
                ->where('specs_status',1)
                ->where('specs_types', 1)
                ->field('specs_id,specs_name,specs_types')
                ->select();
        }

        foreach ($specs as $k => $b){
            $specs[$k]['person'] = [];
            foreach ($personday as $v){
                if ($v['specs_id'] == $b['specs_id']){
                    unset($v['specs_id']);
                    unset($v['goods_id']);
                    unset($v['time']);
                    $v['person_id'] = $v['id'];
                    unset($v['id']);
                    $v['person_price'] = $product_price_exists==2?strval(round($v['person_price'])):strval(ceil($v['person_price']*$discount_rate));
                    $specs[$k]['person'][]  = $v;
                    $specs[$k]['gradeCode'] = "";
                }
            }
            unset( $specs[$k]['specs_types']);
            if(empty($specs[$k]['person'])){
                unset($specs[$k]);
            }
        }
        $specs = array_values($specs);
        $data = [];
        $data['specs'] = $specs;
        $data['typesource'] = 'myself';
        $data['discount_rate'] = $discount_rate;

        return $data;
    }

    //检查商品是否存在
    public function checkExistGoods($goods_id)
    {
        $goods= db('goods g')
            ->join('city c','c.id=g.city_id','left')
            ->field('g.*,g.code as third_code,c.name as city_name,c.groupid as city_groupid,c.kbx_id as kbx_city_id')
            ->where(['g.goods_id'=>$goods_id])->find();
        if(empty($goods_id) || empty($goods)) return ['code'=>400,'msg'=>'商品暂未上架'];
        //去除三方code 接口返回字段冲突
        unset($goods['code']);
        return $goods;
    }

    //获取标签列表
    public function getStandardTags($standard_id)
    {
        return db('standardtags st')->field('t.tag_id as tagId,t.tag_name as tagName,t.icon')
            ->join('tag t','t.tag_id=st.tagid','left')
            ->where('sid',$standard_id)->order("st.sort asc,st.id asc")->select();
    }

    //采购商获取套餐详情
    public function getGoodsPackageSpecByBuyer($standard_id,$supplier_id)
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'标品暂未上架'];
        }
        //判断是否启用帮地接设置的利润
        $noRate = $this->verifyBdjRate($standard,$supplier_id);
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;

        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        //$exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        //$local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //获取折扣
        //$discount_rate = $this->getDiscountRatePriceToB($standard_id);
        $discount_rate = 1;
        //Viator商品
        if(!empty($goods['third_code']) && $goods['show']== 2){
            $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate']??1;//当地汇率    美元/加元
            $data= cache($goods['third_code'].'price');
            if(empty($data)){
                $result['specs'] = [];
            }else{
                unset($data['month_num']);//去除非数组的键值
                //获取viator套餐自定义名称
                list($viatorPackageNameArr,$specNameArr) = (new Standard())->getViatorSpecsDIY($goods['third_code']);
                foreach ($data as $s=>$value){
                    $packages = [
                        'packageId'=>0,
                        'packageName'=>!empty($viatorPackageNameArr[$s])?$viatorPackageNameArr[$s]:$s,
                        'specs'=>[]
                    ];
                    $bandIds = [];
                    foreach ($value as $k=>$v) {
                        foreach ($v['ageBands'] as $k_a=>$v_a) {
                            if(!in_array($v_a['bandId'],$bandIds)){
                                $bandIds[] = $v_a['bandId'];
                                $viatorPrice = ceil($v_a['price']*100)/100;
                                $viatorPriceCNY = ceil($v_a['price']*$local_exchange*100)/100;
                                $packages['specs'][] = [
                                    'specId'=>$v_a['bandId'],
                                    'specName'=>!empty($specNameArr[$v_a['description']])?$specNameArr[$v_a['description']]:$v_a['description'],
                                    'specStock'=>999,
                                    'specPersonsIncUnit'=>1,
                                    'specPersonsPerUnit'=>1,
                                    'specMarketPricePerPerson'=>$viatorPrice,
                                    'specMarketPricePerPersonCNY'=>$viatorPriceCNY,
                                    'specPricePerPerson'=>$viatorPrice,
                                    'specPricePerPersonCNY'=>$viatorPriceCNY,
                                ];
                            }

                        }
                    }
                    $res_data['packages'][] = $packages;
                }
            }
            $res_data['typesource'] ='viator';
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = $currency_code;
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;

        }

        //检查商品类型
        if(!empty($goods['standard_pro']) && $goods['channel_source']=='fareharbor'){
            $faregoods = db("fareharbor_goods")->find($goods['source_id']);
            if(empty($faregoods)) return ['code'=>400,'msg'=>'商品未上架'];
            //获取farehabor利润点
            $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
            $sell_percent_rate = empty($sell_rate)&&$sell_rate['discount_num']?1:$sell_rate['discount_num'];
            $company = $faregoods['company'];
            $currency_code = (new FModel())->getCompanyCurrency($company);
            $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate']??1;//当地汇率    美元/加元
            $item = $faregoods['item_id'];
            $items = (new FModel())->getFareharborData(['company'=>$company]);
            $specsName = db('faregoods_specname')->where('item_id',$item)->select();
            $specs = [];
            foreach ($items as $value){
                if($value['pk']==$item){
                    foreach ($value['customer_prototypes'] as $customer_price){
                        $display_name = "";
                        foreach ($specsName as $s_name){
                            if($s_name['en_name']==$customer_price['display_name']){
                                $display_name = $s_name['ch_name'];break;
                            }
                        }
                        //total_including_tax 单位美分
                        $fareharbor_price = ceil($customer_price['total_including_tax']*$sell_percent_rate)/100;
                        $fareharbor_price_cny = ceil($customer_price['total_including_tax']*$local_exchange*$sell_percent_rate)/100;
                        $specs[] = [
                            'specId'=>$customer_price['pk'],
                            'specName'=>!empty($display_name)?$display_name:$customer_price['display_name'],
                            'specStock'=>999,
                            'specPersonsIncUnit'=>1,
                            'specPersonsPerUnit'=>1,
                            'specMarketPricePerPerson'=>$fareharbor_price,
                            'specMarketPricePerPersonCNY'=>$fareharbor_price_cny,
                            'specPricePerPerson'=>$fareharbor_price,
                            'specPricePerPersonCNY'=>$fareharbor_price_cny,
                        ];
                    }

                }
            }
            if(empty($specs)){
                return ['code'=>400,'msg'=>'暂未查询到价格数据！'];
            }
            $res_data['typesource'] ='fareharbor';
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            $res_data['packages'] = [[
                'packageId'=>0,
                'packageName'=>'DEFAULT',
                'specs'=>$specs
            ]];

            return $res_data;
        }

        $product_price_exists = 0;//价格模式标志
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,service_type,price_section,new_price_flag,base_price_mode,kbx_set_market_price")->find();
            if(!empty($product) && $product['base_price_mode']==1) {
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        //汇率问题
        $local_exchange = 1;
        //用车类产品价格统一为人民币
        if(!empty($product['service_type']) && $product['service_type']==5) $product['currency'] = 'CNY';
        if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
            $local_exchange = $exchangeRate['exchange_rate']??$local_exchange;
        }
        if($product_price_exists==2){
            //获取套餐
            $specs = db('product_base_specs ps')
                ->join('product_base_package pp','pp.id=ps.package_id','left')
                ->where(['pp.product_id'=>$product['id']])
                ->where('ps.status',1)
                ->field('ps.id as specId,ps.name as specName,
                ps.num as specStock,ps.inc_order_num as specPersonsIncUnit,
                ps.minorder_num as specPersonsPerUnit,ps.package_id as packageId,
                pp.name as packageName,ps.special as isIgnore')
                ->select();
            $specs_ids = array_column($specs,'specId');
            $total_cost = $noRate?'min(CONVERT(total_cost,UNSIGNED)) as specPricePerPerson':'min(CONVERT(total_cost,UNSIGNED))*100/(100-ps.bdj_rate) as specPricePerPerson';
            $dayprice = db('product_base_dailyprice pd')
                ->join('product_base_specs ps','pd.specs_id=ps.id','left')
                ->field('pd.id,pd.specs_id,'.$total_cost.',min(pd.price) as specMarketPricePerPerson')
                ->where(['pd.specs_id'=>['in',$specs_ids],'time'=>['egt',date('Y-m-d')]])
                ->group('pd.specs_id')
                ->select();
            if(empty($dayprice) && empty($standard['allow_everyone_quote'])
                && !empty($standard['is_group_exhibition'])){
                //mysql 5.7版本groupby orderby 联合使用 需在子查询中使用having 1=1限定
                $total_cost = $noRate?'CONVERT(pd.total_cost,UNSIGNED) as specPricePerPerson':'CONVERT(pd.total_cost,UNSIGNED)*100/(100-ps.bdj_rate) as specPricePerPerson';
                $subQuery = db('product_base_dailyprice pd')
                    ->join('product_base_specs ps','pd.specs_id=ps.id','left')
                    ->field('pd.id,pd.specs_id,pd.time,'.$total_cost.',pd.price as specMarketPricePerPerson')
                    ->where(['pd.specs_id'=>['in',$specs_ids]])
                    ->having('1=1')
                    ->order('pd.time desc')
                    ->buildSql();
                $dayprice = db::table($subQuery.' pd_temp')
                    ->field('pd_temp.id,pd_temp.specs_id,pd_temp.specPricePerPerson,pd_temp.specMarketPricePerPerson')
                    ->group('pd_temp.specs_id')
                    ->select();
                if(empty($dayprice)) $specs = [];
            }elseif(empty($dayprice)){
                $specs = [];
            }
            foreach ($specs as $spec_key=>$spec_value){
                $specs[$spec_key]['specPricePerPerson'] = $specs[$spec_key]['specMarketPricePerPerson'] = 0;
                $specs[$spec_key]['specPricePerPersonCNY'] = $specs[$spec_key]['specMarketPricePerPersonCNY'] = 0;
                foreach ($dayprice as $price_key=>$price_value){
                    if($spec_value['specId']==$price_value['specs_id']){
                        $specs[$spec_key]['specPricePerPerson'] = ceil($price_value['specPricePerPerson']);
                        $specs[$spec_key]['specPricePerPersonCNY'] = ceil($price_value['specPricePerPerson']*$local_exchange);
                        $specs[$spec_key]['specMarketPricePerPerson'] = ceil($price_value['specMarketPricePerPerson']);
                        $specs[$spec_key]['specMarketPricePerPersonCNY'] = ceil($price_value['specMarketPricePerPerson']*$local_exchange);
                        unset($dayprice[$price_key]);
                    }
                }
            }
        }elseif($product_price_exists==1){
            //获取套餐
            $specs = db('product_specs ps')
                ->join('product_package pp','pp.id=ps.package_id','left')
                ->where(['pp.product_id'=>$product['id']])
                ->where('ps.status',1)
                ->field('ps.id as specId,ps.name as specName,
                ps.num as specStock,ps.inc_order_num as specPersonsIncUnit,
                ps.minorder_num as specPersonsPerUnit,ps.package_id as packageId,
                pp.name as packageName,"0" as isIgnore')
                ->select();
            $specs_ids = array_column($specs,'specId');
            $dayprice = db('product_dailyprice pd')
                ->field('pd.id,pd.specs_id,min(pd.price) as specPricePerPerson,min(pd.price) as specMarketPricePerPerson')
                ->where(['pd.specs_id'=>['in',$specs_ids],'time'=>['egt',date('Y-m-d')]])
                ->group('pd.specs_id')
                ->select();
            if(empty($dayprice) && empty($standard['allow_everyone_quote'])
                && !empty($standard['is_group_exhibition'])){
                //mysql 5.7版本groupby orderby 联合使用 需在子查询中使用having 1=1限定
                $subQuery = db('product_dailyprice pd')
                    ->field('pd.id,pd.specs_id,pd.price as specPricePerPerson,pd.price as specMarketPricePerPerson')
                    ->where(['pd.specs_id'=>['in',$specs_ids]])
                    ->having('1=1')
                    ->order('pd.time desc')
                    ->buildSql();
                $dayprice = db::table($subQuery.' pd_temp')
                    ->field('pd_temp.id,pd_temp.specs_id,pd_temp.specPricePerPerson,pd_temp.specMarketPricePerPerson')
                    ->group('pd_temp.specs_id')
                    ->select();
                if(empty($dayprice)) $specs = [];
            }elseif(empty($dayprice)){
                $specs = [];
            }
            foreach ($specs as $spec_key=>$spec_value){
                $specs[$spec_key]['specPricePerPerson'] = $specs[$spec_key]['specMarketPricePerPerson'] = 0;
                $specs[$spec_key]['specPricePerPersonCNY'] = $specs[$spec_key]['specMarketPricePerPersonCNY'] = 0;
                foreach ($dayprice as $price_key=>$price_value){
                    if($spec_value['specId']==$price_value['specs_id']){
                        $specs[$spec_key]['specPricePerPerson'] = ceil($price_value['specPricePerPerson']);
                        $specs[$spec_key]['specPricePerPersonCNY'] = ceil($price_value['specPricePerPerson']*$local_exchange);
                        $specs[$spec_key]['specMarketPricePerPerson'] = ceil($price_value['specMarketPricePerPerson']);
                        $specs[$spec_key]['specMarketPricePerPersonCNY'] = ceil($price_value['specMarketPricePerPerson']*$local_exchange);
                        unset($dayprice[$price_key]);
                    }
                }
            }
        }else{
            //获取套餐
            $specs = db('person ps')
                ->join('specs pp','pp.specs_id=ps.specs_id','left')
                ->where(['pp.goods_id'=>$goods_id])
                ->where('ps.person_status',1)
                ->field('ps.person_id as specId,ps.person_name as specName,
                ps.person_num as specStock,ps.inc_order_num as specPersonsPerUnit,
                ps.minorder_num as specPersonsPerUnit,ps.specs_id as packageId,
                pp.specs_id as packageName,"0" as isIgnore')
                ->select();
            $specs_ids = array_column($specs,'specId');
            $dayprice = db('personday pd')
                ->field('pd.id,pd.person_id,min(pd.person_price) as specPricePerPerson,min(pd.person_price) as specMarketPricePerPerson')
                ->where(['pd.person_id'=>['in',$specs_ids],'time'=>['egt',date('Y-m-d')]])
                ->group('pd.person_id')
                ->select();
            if(empty($dayprice) && empty($standard['allow_everyone_quote'])
                && !empty($standard['is_group_exhibition'])){
                //mysql 5.7版本groupby orderby 联合使用 需在子查询中使用having 1=1限定
                $subQuery = db('personday pd')
                    ->field('pd.id,pd.person_id,pd.person_price as specPricePerPerson,pd.person_price as specMarketPricePerPerson')
                    ->where(['pd.person_id'=>['in',$specs_ids]])
                    ->having('1=1')
                    ->order('pd.time desc')
                    ->buildSql();
                $dayprice = db::table($subQuery.' pd_temp')
                    ->field('pd_temp.id,pd_temp.person_id,pd_temp.specPricePerPerson,pd_temp.specMarketPricePerPerson')
                    ->group('pd_temp.person_id')
                    ->select();
                if(empty($dayprice)) $specs = [];
            }elseif(empty($dayprice)){
                $specs = [];
            }
            foreach ($specs as $spec_key=>$spec_value){
                $specs[$spec_key]['specPricePerPerson'] = $specs[$spec_key]['specMarketPricePerPerson'] = 0;
                $specs[$spec_key]['specPricePerPersonCNY'] = $specs[$spec_key]['specMarketPricePerPersonCNY'] = 0;
                foreach ($dayprice as $price_key=>$price_value){
                    if($spec_value['specId']==$price_value['person_id']){
                        $specs[$spec_key]['specPricePerPerson'] = ceil($price_value['specPricePerPerson']);
                        $specs[$spec_key]['specPricePerPersonCNY'] = ceil($price_value['specPricePerPerson']*$local_exchange);
                        $specs[$spec_key]['specMarketPricePerPerson'] = ceil($price_value['specMarketPricePerPerson']);
                        $specs[$spec_key]['specMarketPricePerPersonCNY'] = ceil($price_value['specMarketPricePerPerson']*$local_exchange);
                        unset($dayprice[$price_key]);
                    }
                }
            }
        }

        if(empty($specs)) return ['code'=>401,'msg'=>'暂无日历价格数据'];
        $packages = [];
        $package_ids = [];
        foreach ($specs as $key=>$value){
            if(!in_array($value['packageId'],$package_ids)){
                $packages[] = [
                    'packageId'=>$value['packageId'],
                    'packageName'=>$value['packageName']
                ];
                $package_ids[] = $value['packageId'];
            }
        }
        foreach ($packages as $p_k=>$p_v){
            $packages[$p_k]['specs'] = [];
            foreach ($specs as $s_k=>$s_v){
                if($s_v['packageId']==$p_v['packageId']){
                    unset($s_v['packageId'],$s_v['packageName']);
                    $packages[$p_k]['specs'][] = $s_v;
                    unset($specs[$s_k]);
                }
            }
        }
        $data['typesource'] ='myself';
        $data['basePricrMode'] = !empty($product['base_price_mode'])?true:false;
        $data['newPriceMode'] = !empty($product['new_price_flag'])?true:false;
        $data['bdjSetMarketPrice'] = !empty($product['kbx_set_market_price'])?true:false;
        $data['currency'] = !empty($product['currency'])?$product['currency']:'CNY';
        $data['exchangeRate'] = $local_exchange;
        $data['packages'] = $packages;
        return $data;
    }

    //采购商获取套餐详情
    public function getFeaturedGoodsPackageSpecByBuyer($standard_id,$supplier_id)
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'标品暂未上架'];
        }
        //判断是否启用帮地接设置的利润
        $noRate = $this->verifyBdjRate($standard,$supplier_id);
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;
        //根据订单类型判断是否为特色商品 否则提示
        if($goods['orderType']!=="FeaturedProduct"){
            return ['code'=>400,'msg'=>'该产品不属于特色商品，请检查后重新获取！'];
        }
        $product_price_exists = 0;//价格模式标志
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode,kbx_set_market_price")->find();
            if(!empty($product) && $product['base_price_mode']==1) {
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        //汇率问题
        $local_exchange = 1;
        if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
            $local_exchange = $exchangeRate['exchange_rate']??$local_exchange;
        }
        $today = date('Y-m-d');
        if($product_price_exists==2){
            //获取套餐
            $specs = db('product_base_specs ps')
                ->join('product_base_package pp','pp.id=ps.package_id','left')
                ->where(['pp.product_id'=>$product['id']])
                ->where('ps.status',1)
                ->field('ps.id as specId,ps.name as specName,
                ps.num as specStock,ps.inc_order_num as specPersonsIncUnit,
                ps.minorder_num as specPersonsPerUnit,ps.package_id as packageId,
                pp.name as packageName,ps.special as isIgnore')
                ->select();
            $specs_ids = array_column($specs,'specId');
            $total_cost = $noRate?'pd.total_cost as specPricePerPerson':'pd.total_cost*100/(100-ps.bdj_rate) as specPricePerPerson';
            $dayprice = db('product_base_dailyprice pd')
                ->join('product_base_specs ps','pd.specs_id=ps.id','left')
                ->field('pd.id,pd.specs_id,'.$total_cost.',pd.price as specMarketPricePerPerson')
                ->where(['pd.specs_id'=>['in',$specs_ids],'time'=>['egt',$today]])
                ->group('pd.specs_id')
                ->select();
            foreach ($specs as $spec_key=>$spec_value){
                $specs[$spec_key]['specPricePerPerson'] = $specs[$spec_key]['specMarketPricePerPerson'] = 0;
                $specs[$spec_key]['specPricePerPersonCNY'] = $specs[$spec_key]['specMarketPricePerPersonCNY'] = 0;
                foreach ($dayprice as $price_key=>$price_value){
                    if($spec_value['specId']==$price_value['specs_id']){
                        $specs[$spec_key]['specPricePerPerson'] = ceil($price_value['specPricePerPerson']);
                        $specs[$spec_key]['specPricePerPersonCNY'] = ceil($price_value['specPricePerPerson']*$local_exchange);
                        $specs[$spec_key]['specMarketPricePerPerson'] = ceil($price_value['specMarketPricePerPerson']);
                        $specs[$spec_key]['specMarketPricePerPersonCNY'] = ceil($price_value['specMarketPricePerPerson']*$local_exchange);
                        unset($dayprice[$price_key]);
                    }
                }
            }
        }elseif($product_price_exists==1){
            //获取套餐
            $specs = db('product_specs ps')
                ->join('product_package pp','pp.id=ps.package_id','left')
                ->where(['pp.product_id'=>$product['id']])
                ->where('ps.status',1)
                ->field('ps.id as specId,ps.name as specName,
                ps.num as specStock,ps.inc_order_num as specPersonsIncUnit,
                ps.minorder_num as specPersonsPerUnit,ps.package_id as packageId,
                pp.name as packageName,"0" as isIgnore')
                ->select();
            $specs_ids = array_column($specs,'specId');
            $dayprice = db('product_dailyprice pd')
                ->field('pd.id,pd.specs_id,pd.price as specPricePerPerson,pd.price as specMarketPricePerPerson')
                ->where(['pd.specs_id'=>['in',$specs_ids],'time'=>['egt',$today]])
                ->group('pd.specs_id')
                ->select();
            foreach ($specs as $spec_key=>$spec_value){
                $specs[$spec_key]['specPricePerPerson'] = $specs[$spec_key]['specMarketPricePerPerson'] = 0;
                $specs[$spec_key]['specPricePerPersonCNY'] = $specs[$spec_key]['specMarketPricePerPersonCNY'] = 0;
                foreach ($dayprice as $price_key=>$price_value){
                    if($spec_value['specId']==$price_value['specs_id']){
                        $specs[$spec_key]['specPricePerPerson'] = ceil($price_value['specPricePerPerson']);
                        $specs[$spec_key]['specPricePerPersonCNY'] = ceil($price_value['specPricePerPerson']*$local_exchange);
                        $specs[$spec_key]['specMarketPricePerPerson'] = ceil($price_value['specMarketPricePerPerson']);
                        $specs[$spec_key]['specMarketPricePerPersonCNY'] = ceil($price_value['specMarketPricePerPerson']*$local_exchange);
                        unset($dayprice[$price_key]);
                    }
                }
            }
        }else{
            //获取套餐
            $specs = db('person ps')
                ->join('specs pp','pp.specs_id=ps.specs_id','left')
                ->where(['pp.goods_id'=>$goods_id])
                ->where('ps.person_status',1)
                ->field('ps.person_id as specId,ps.person_name as specName,
                ps.person_num as specStock,ps.inc_order_num as specPersonsPerUnit,
                ps.minorder_num as specPersonsPerUnit,ps.specs_id as packageId,
                pp.specs_id as packageName,"0" as isIgnore')
                ->select();
            $specs_ids = array_column($specs,'specId');
            $dayprice = db('personday pd')
                ->field('pd.id,pd.person_id,pd.person_price as specPricePerPerson,pd.person_price as specMarketPricePerPerson')
                ->where(['pd.person_id'=>['in',$specs_ids],'time'=>['egt',$today]])
                ->group('pd.person_id')
                ->select();
            foreach ($specs as $spec_key=>$spec_value){
                $specs[$spec_key]['specPricePerPerson'] = $specs[$spec_key]['specMarketPricePerPerson'] = 0;
                $specs[$spec_key]['specPricePerPersonCNY'] = $specs[$spec_key]['specMarketPricePerPersonCNY'] = 0;
                foreach ($dayprice as $price_key=>$price_value){
                    if($spec_value['specId']==$price_value['person_id']){
                        $specs[$spec_key]['specPricePerPerson'] = ceil($price_value['specPricePerPerson']);
                        $specs[$spec_key]['specPricePerPersonCNY'] = ceil($price_value['specPricePerPerson']*$local_exchange);
                        $specs[$spec_key]['specMarketPricePerPerson'] = ceil($price_value['specMarketPricePerPerson']);
                        $specs[$spec_key]['specMarketPricePerPersonCNY'] = ceil($price_value['specMarketPricePerPerson']*$local_exchange);
                        unset($dayprice[$price_key]);
                    }
                }
            }
        }

        $packages = [];
        $package_ids = [];
        foreach ($specs as $key=>$value){
            if(!in_array($value['packageId'],$package_ids)){
                $packages[] = [
                    'packageId'=>$value['packageId'],
                    'packageName'=>$value['packageName']
                ];
                $package_ids[] = $value['packageId'];
            }
        }
        foreach ($packages as $p_k=>$p_v){
            $packages[$p_k]['specs'] = [];
            foreach ($specs as $s_k=>$s_v){
                if($s_v['packageId']==$p_v['packageId']){
                    unset($s_v['packageId'],$s_v['packageName']);
                    $packages[$p_k]['specs'][] = $s_v;
                    unset($specs[$s_k]);
                }
            }
        }
        $data['typesource'] ='myself';
        $data['basePricrMode'] = !empty($product['base_price_mode'])?true:false;
        $data['newPriceMode'] = !empty($product['new_price_flag'])?true:false;
        $data['bdjSetMarketPrice'] = !empty($product['kbx_set_market_price'])?true:false;
        $data['currency'] = !empty($product['currency'])?$product['currency']:'CNY';
        $data['exchangeRate'] = $local_exchange;
        $data['packages'] = $packages;
        return $data;
    }

    //获取商品套餐日历价格
    public function getGoodsSpecByBuyer($standard_id,$year='',$month='',$duration=1,$supplier_id='')
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'标品暂未上架'];
        }
        //判断是否启用帮地接设置的利润
        $noRate = $this->verifyBdjRate($standard,$supplier_id);
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;
        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //获取折扣
//        $discount_rate = $this->getDiscountRatePriceToB($standard_id);
        $discount_rate = 1;
        //检查商品类型
        if(!empty($goods['standard_pro']) && $goods['channel_source']=='fareharbor'){
            $faregoods = db("fareharbor_goods")->find($goods['source_id']);
            if(empty($faregoods)) return ['code'=>400,'msg'=>'商品未上架'];
            $company = $faregoods['company'];
            $item = $faregoods['item_id'];
            $currency_code = (new Fmodel())->getCompanyCurrency($company);
            $exchangeArr = db("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
            $packages = (new F())->getPackageByLastMonth($company,$item,$local_exchange,time(),3);
            if(empty($packages)) return ['code'=>400,'msg'=>'商品暂未配置价格'];
            $sale_time = !empty($packages[0]['time'])?$packages[0]['time']:'';
            $res_data['packages'] = $packages;
            $res_data['goods_id'] = $goods_id;
            $res_data['discount_rate'] = $discount_rate;//不启用 折扣模式
            $res_data['type'] = 'fareharbor';
            $res_data['sale_time'] = $sale_time;
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;
        }

        //Viator商品
        if(!empty($goods['third_code']) && $goods['show']== 2){
            $data = cache($goods['third_code'].'price');
            if(empty($data)){
                return ['code'=>400,'msg'=>'商品未配置价格'];
            }else{
                unset($data['month_num']);//去除非数组的键值
                //获取viator套餐自定义名称
                list($viatorPackageNameArr,$specNameArr) = (new Standard())->getViatorSpecsDIY($goods['third_code']);
                foreach ($data as $s=>$value){
                    //匹配自定义套餐名
                    foreach ($value as $k=>$v) {
                        $specs = [];
                        foreach ($v['ageBands'] as $k_a=>$v_a) {
                            $vaitor_price = ceil($v_a['price']*100)/100;
                            $vaitor_cny_price = ceil($v_a['price']*$local_exchange*100)/100;
                            $specs[] = [
                                'packageId'=>0,
                                'packageName'=>!empty($viatorPackageNameArr[$s])?$viatorPackageNameArr[$s]:$s,
                                'specId'=>$v_a['bandId'],
                                'specName'=>!empty($specNameArr[$v_a['description']])?$specNameArr[$v_a['description']]:$v_a['description'],
                                'specStock'=>999,
                                'specPersonsIncUnit'=>1,
                                'specPersonsPerUnit'=>1,
                                'specMarketPricePerPerson'=>$vaitor_price,
                                'specPricePerPerson'=>$vaitor_price,
                                'specMarketPricePerPersonCNY'=>$vaitor_cny_price,
                                'specPricePerPersonCNY'=>$vaitor_cny_price,
                            ];
                        }
                        $packages[] = [
                            'time'=>$v['bookingDate'],
                            'specs'=>$specs
                        ];
                    }
                }
            }
            if(empty($packages)) return ['code'=>400,'msg'=>'商品暂未配置价格'];
            //如果存在重复日期的套餐进行合并
            $dates = [];
            foreach ($packages as $package_k=>$package_v){
                if(!in_array($package_v['time'],$dates)){
                    $dates[$package_k] = $package_v['time'];
                }else{
                    $package_index = array_search($package_v['time'],$dates);
                    $packages[$package_index]['specs'] = array_merge($packages[$package_index]['specs'],$package_v['specs']);
                    unset($packages[$package_k]);
                }
            }

            $sale_time = !empty($packages[0]['time'])?$packages[0]['time']:'';
            $res_data['packages'] = array_values($packages);
            $res_data['goods_id'] = $goods_id;
            $res_data['discount_rate'] = $discount_rate;//不启用 折扣模式
            $res_data['type'] = 'viator';
            $res_data['sale_time'] = $sale_time;
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;
        }

        //产品价格替换
        $product_id = '';
        $product_section = '';
        $product_price_exists = 0;//是否存在产品价格
        $bdjSetMarketPrice = 0;//设置统一售价
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode,kbx_set_market_price")->find();
            if(!empty($product) && $product['base_price_mode']==1){
                $product_id = $product['id'];
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_id = $product['id'];
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        //获取可售卖的时间 截止天数+当前时间
        //地接社类标品
        if(!empty($standard['s_endDays'])){
            $sale_time = $standard['s_endDays']==1?strtotime('+1 day'):strtotime('+'.$standard['s_endDays'].' days');
        }else{
            $standardtrip = db('standardtrip')->where('sid',$standard_id)->find();
            if(!empty($standardtrip['endDays']) && $standardtrip['endDays']>0){
                $sale_time = $standardtrip['endDays']==1?strtotime('+1 day'):strtotime('+'.$standardtrip['endDays'].' days');
            }else{
                $sale_time = time();
            }
        }
        $sale_time = date('Y-m-d',$sale_time);
        $start_day = $end_day = '';
        if(!empty($year) && !empty($month)){
            $month = $month < 10 ? '0'.$month : $month;
            $start_day = $year.'-'.$month.'-01';
            $start_time = strtotime($start_day);
            $end_day = date("Y-m-d",strtotime('+'.$duration.' months',$start_time));
            $start_day = max([$sale_time,$start_day]);//获取比较大的起始日期
        }
        $where = [];
        if($product_price_exists==2){
            $where['pd.product_id'] = $product_id;
            //获取所有的日期的价格设置
            $total_cost = $noRate?'pd.total_cost as specPricePerPerson':'pd.total_cost*100/(100-ps.bdj_rate) as specPricePerPerson';
            if(!empty($start_day) && !empty($end_day)){
                $where['pd.time'] = [['egt',$start_day],['lt',$end_day]];
            }else{
                $where['pd.time'] = ['egt',$sale_time];
            }
            $personday = db('product_base_dailyprice pd')
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->where($where)
                ->field("pd.name as specName,".$total_cost.",pd.price as specMarketPricePerPerson,pd.num as specStock,pd.package_id as packageId,pd.specs_id as specId,pd.minorder_num as specPersonsPerUnit,pd.inc_order_num as specPersonsIncUnit,time")
                ->order("pd.time asc")
                ->select();

        }elseif($product_price_exists==1){
            $where['product_id'] = $product_id;
            //获取所有的日期的价格设置
            if(!empty($start_day) && !empty($end_day)){
                $where['time'] = [['egt',$start_day],['lt',$end_day]];
            }else{
                $where['time'] = ['egt',$sale_time];
            }
            //获取所有的日期的价格设置
            $personday = db('product_dailyprice')
                ->where($where)
                ->field("name as specName,price as specPricePerPerson,num as specStock,package_id as packageId,specs_id as specId,minorder_num as specPersonsPerUnit,inc_order_num as specPersonsIncUnit,time")
                ->order("time asc")
                ->select();
        }else{
            $where['goods_id'] = $goods_id;
            //获取所有的日期的价格设置
            if(!empty($start_day) && !empty($end_day)){
                $where['time'] = [['egt',$start_day],['lt',$end_day]];
            }else{
                $where['time'] = ['egt',$sale_time];
            }
            //获取所有的日期的价格设置
            $personday = db('personday')
                ->where($where)
                ->field("person_name as specName,person_price as specPricePerPerson,person_num as specStock,specs_id as packageId,person_id as specId,minorder_num as specPersonsPerUnit,inc_order_num as specPersonsIncUnit,time")
                ->order("time asc")
                ->select();
        }
        if(empty($personday)) return ['code'=>400,'msg'=>'暂未配置价格'];
        //汇率问题
        $exchange_rate = 1;
        if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
            $exchange_rate = $exchangeRate['exchange_rate']??$exchange_rate;
        }
        foreach ($personday as $p_k=>$p_v){
            if($product_price_exists==2){
                //默认人民币汇率
                $personday[$p_k]['specPricePerPersonCNY'] = $personday[$p_k]['specPricePerPerson'] = ceil($p_v['specPricePerPerson']);
                $personday[$p_k]['specMarketPricePerPersonCNY'] = $personday[$p_k]['specMarketPricePerPerson'] = ceil($p_v['specMarketPricePerPerson']);
                if($exchange_rate > 1){
                    $personday[$p_k]['specPricePerPersonCNY'] = ceil(round($p_v['specPricePerPerson'])*$exchange_rate);
                    $personday[$p_k]['specMarketPricePerPersonCNY'] = ceil(round($p_v['specMarketPricePerPerson'])*$exchange_rate);
                }
            }else{
                $personday[$p_k]['specMarketPricePerPersonCNY'] = '';
                $personday[$p_k]['specMarketPricePerPerson'] = '';
                $personday[$p_k]['specPricePerPersonCNY'] = $personday[$p_k]['specPricePerPerson'] = ceil($p_v['specPricePerPerson']*$discount_rate);
            }
        }
        $days = array_values(array_unique(array_column($personday,"time")));

        foreach ($days as $day_key=>$day_value){
            $days[$day_key] = [];
            foreach ($personday as $p_k=>$p_v){
                if($p_v['time']==$day_value){
                    $days[$day_key]['time'] = $day_value;
                    unset($p_v['time']);
                    $days[$day_key]['specs'][] = $p_v;
                    unset($personday[$p_k]);
                }
            }
        }
        if(empty($days)) return ['code'=>400,'msg'=>'暂未配置价格'];
//        foreach ($days as $day_key=>$day_value){
//            $saleNum = [];
//            $price = [];
//            foreach ($day_value['specs'] as $specs){
//                $saleNum[] = $specs['specStock'];
//                $price[] = $product_price_exists==2?round($specs['specPricePerPerson']):ceil($specs['specPricePerPerson']*$discount_rate);
//            }
//            $min_price = 0;
//            $min_salenum = 0;
//            if(!empty($price)){
//                $min_price = min($price);
//                $min_key = array_search($min_price,$price);
//                $min_salenum = $saleNum[$min_key];
//            }
//            $days[$day_key]['minPrice'] = $min_price;
//            $days[$day_key]['minStock'] = $min_salenum;
//            unset($days[$day_key]['specs']);
//        }
        $data['packages'] = $days;
        $data['goods_id'] = $goods_id;
        $data['discount_rate'] = $discount_rate;
        $data['type'] = 'myself';
        $data['sale_time'] = $sale_time;
        $data['basePricrMode'] = !empty($product['base_price_mode'])?true:false;
        $data['newPriceMode'] = !empty($product['new_price_flag'])?true:false;
        $data['bdjSetMarketPrice'] = !empty($product['kbx_set_market_price'])?true:false;
        $data['currency'] = !empty($product['currency'])?$product['currency']:'CNY';
        $data['exchangeRate'] = $exchange_rate;
        return $data;
    }

    //获取套餐详情
    public function getGoodsSpecInfoByBuyer($standard_id,$time,$supplier_id='')
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'标品暂未上架'];
        }
        //判断是否启用帮地接设置的利润
        $noRate = $this->verifyBdjRate($standard,$supplier_id);
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;
        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //获取折扣
        //$discount_rate = $this->getDiscountRatePriceToB($standard_id);
        $discount_rate = 1;
        if(!empty($goods['third_code']) && $goods['show']==2){
            //By Suley
            //修改过的自定义套餐名称
            $where_name['code'] = $goods['third_code'];
            $specsName = db('specsname')->where($where_name)->select();
            $nameArr = array();
            if(!empty($specsName)){
                foreach ($specsName as $k_name=>$v_name){
                    $nameArr[$v_name['grade_code']] = $v_name['new_name'];
                }
            }

            $data = cache($goods['third_code'].'price');
            if(empty($data)){
                return ['code'=>400,'msg'=>'商品未配置价格'];
            }else{
                unset($data['month_num']);//去除非数组的键值
                foreach ($data as $s=>$value){
                    foreach ($value as $k=>$v) {
                        if($v['bookingDate']==$time){
                            $specs = [];
                            foreach ($v['ageBands'] as $k_a=>$v_a) {
                                $vaitor_price = ceil($v_a['price']*100)/100;
                                $vaitor_cny_price = ceil($v_a['price']*$local_exchange*100)/100;
                                $specs[] = [
                                    'personId'=>$k_a,
                                    'specId'=>$v_a['bandId'],
                                    'specName'=>$v_a['description'],
                                    'age'=>$v_a['age'],
                                    'specStock'=>999,
                                    'specPersonsIncUnit'=>1,
                                    'specPersonsPerUnit'=>1,
                                    'specMarketPricePerPerson'=>$vaitor_price,
                                    'specPricePerPerson'=>$vaitor_price,
                                    'specMarketPricePerPersonCNY'=>$vaitor_cny_price,
                                    'specPricePerPersonCNY'=>$vaitor_cny_price,
                                ];
                            }
                            $packages[] = [
                                'packageId'=>0,
                                'packageName'=>$s,
                                'packageDesc'=>!empty($nameArr[$s]) ? $nameArr[$s] : '',
                                'specs'=>$specs
                            ];
                        }
                    }
                }
            }
            if(empty($packages)) return ['code'=>400,'msg'=>'商品暂未配置价格'];
            //如果存在重复日期的套餐进行合并
//            $dates = [];
//            foreach ($packages as $package_k=>$package_v){
//                if(!in_array($package_v['packageName'],$dates)){
//                    $dates[$package_k] = $package_v['packageName'];
//                }else{
//                    $package_index = array_search($package_v['packageName'],$dates);
//                    $packages[$package_index]['specs'] = array_merge($packages[$package_index]['specs'],$package_v['specs']);
//                    unset($packages[$package_k]);
//                }
//            }

            $result['typesource'] = 'viator';
            $res_data['packages'] = $packages;
            $res_data['discount_rate'] = $discount_rate;//不启用 折扣模式
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;
        }
        //检查fareharbor类型
        if(!empty($goods['standard_pro']) && $goods['channel_source']=='fareharbor'){
            $faregoods = db("fareharbor_goods")->find($goods['source_id']);
            if(empty($faregoods)) return ['code'=>400,'msg'=>'暂未配置套餐价格'];
            $company = $faregoods['company'];
            $item = $faregoods['item_id'];
            $currency_code = (new Fmodel())->getCompanyCurrency($company);
            $exchangeArr = db("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
            $date = $time;
            $packages = (new F())->getPackageByOneDay($company,$item,$local_exchange,$date);
            if(empty($packages)) return ['code'=>400,'msg'=>'暂未配置当日套餐价格'];
            $res_data['packages'] = $packages;
            $res_data['discount_rate'] = $discount_rate;//不启用 折扣模式
            $res_data['typesource'] = 'fareharbor';
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;
        }

        //是否启用忽略日期设置 当前日期不一定存在套餐去最近的套餐
        $isIgnoreTime = in_array($goods['orderType'],['FeaturedProduct']);
        $where = [];
        $where['goods_id']  = $goods_id;
        $where['time']      = $isIgnoreTime ? ['egt',$time] : $time;

        //产品价格替换
        $product_id = '';
        $product_section = '';
        $product_price_exists = 0;//是否存在产品价格
        $bdjSetMarketPrice = 0;//设置统一售价
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode,kbx_set_market_price")->find();
            if(!empty($product) && $product['base_price_mode']==1) {
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        if($product_price_exists==2){
            $where_p['pd.product_id']  = $product['id'];
            $where_p['pd.time']        = $isIgnoreTime ? ['egt',$time] : $time;
            $total_cost = $noRate?'pd.total_cost as specPricePerPerson':'pd.total_cost*100/(100-ps.bdj_rate) as specPricePerPerson';
            //获取规格
            $personday = db('product_base_dailyprice pd')
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->where($where_p)
                ->field('pd.id as personId,pd.name as specName,'.$total_cost.',pd.price as specMarketPricePerPerson,pd.num as specStock,pd.package_id as packageId,pd.specs_id as specId,pd.minorder_num as specPersonsPerUnit,pd.inc_order_num as specPersonsIncUnit,time')
                ->order('pd.time asc,pd.specs_id asc')
                ->select();
            //获取套餐
            $packages = db('product_base_package')
                ->where(['product_id'=>$product['id']])
                ->where('status',1)
                ->field('id as packageId,name as packageName')
                ->select();
        }elseif($product_price_exists==1){
            $where_p['product_id']  = $product['id'];
            $where_p['time']        = $isIgnoreTime ? ['egt',$time] : $time;
            //获取规格
            $personday = db('product_dailyprice')
                ->where($where_p)
                ->field('id as personId,name as specName,price as specPricePerPerson,num as specStock,package_id as packageId,specs_id as specId,minorder_num as specPersonsPerUnit,inc_order_num as specPersonsIncUnit,time')
                ->order('time asc,specs_id asc')
                ->select();
            //获取套餐
            $packages = db('product_package')
                ->where(['product_id'=>$product['id']])
                ->where('status',1)
                ->field('id as packageId,name as packageName')
                ->select();
        }else{
            //获取规格
            $personday =  db('personday')
                ->where($where)
                ->field('id as personId,person_name as specName,person_price as specPricePerPerson,person_num as specStock,specs_id as packageId,person_id as specId,minorder_num as specPersonsPerUnit,inc_order_num as specPersonsIncUnit,time')
                ->order('time asc,id asc')
                ->select();
            //获取套餐
            $packages = db('specs')
                ->where(['goods_id'=>$goods_id])
                ->where('specs_status',1)
                ->where('specs_types', 1)
                ->field('specs_id as packageId,specs_name as packageName')
                ->select();
        }
        //汇率问题
        $exchange_rate = 1;
        if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
            $exchange_rate = $exchangeRate['exchange_rate']??$exchange_rate;
        }
        foreach ($personday as $p_k=>$p_v){
            if($product_price_exists==2){
                //默认人民币汇率
                $personday[$p_k]['specPricePerPersonCNY'] = $personday[$p_k]['specPricePerPerson'] = ceil($p_v['specPricePerPerson']);
                $personday[$p_k]['specMarketPricePerPersonCNY'] = $personday[$p_k]['specMarketPricePerPerson'] = ceil($p_v['specMarketPricePerPerson']);
                if($exchange_rate > 1){
                    $personday[$p_k]['specPricePerPersonCNY'] = ceil(round($p_v['specPricePerPerson'])*$exchange_rate);
                    $personday[$p_k]['specMarketPricePerPersonCNY'] = ceil(round($p_v['specMarketPricePerPerson'])*$exchange_rate);
                }
            }else{
                $personday[$p_k]['specMarketPricePerPersonCNY'] = '';
                $personday[$p_k]['specMarketPricePerPerson'] = '';
                $personday[$p_k]['specPricePerPersonCNY'] = $personday[$p_k]['specPricePerPerson'] = ceil($p_v['specPricePerPerson']*$discount_rate);
            }
        }
        foreach ($packages as $k => $b){
            $packages[$k]['specs'] = [];
            foreach ($personday as $v){
                if ($v['packageId'] == $b['packageId']){
                    unset($v['packageId']);
                    unset($v['goods_id']);
                    unset($v['time']);
                    $v['specPricePerPerson'] = $product_price_exists==2?(round($v['specPricePerPerson'])):strval(ceil($v['specPricePerPerson']*$discount_rate));
                    $packages[$k]['specs'][]  = $v;
                    $packages[$k]['gradeCode'] = "";
                }
            }
            if(empty($packages[$k]['specs'])){
                unset($packages[$k]);
            }
        }
        $packages = array_values($packages);
        $data = [];
        $data['packages'] = $packages;
        $data['basePricrMode'] = !empty($product['base_price_mode'])?true:false;
        $data['newPriceMode'] = !empty($product['new_price_flag'])?true:false;
        $data['bdjSetMarketPrice'] = !empty($product['kbx_set_market_price'])?true:false;
        $data['currency'] = !empty($product['currency'])?$product['currency']:"CNY";
        $data['typesource'] = 'myself';
        $data['discount_rate'] = $discount_rate;
        $data['exchangeRate'] = $exchange_rate;

        return $data;
    }
    //验证是否按照供应商基础价格返回
    public function verifyBdjRate($standard=[],$supplier_id='')
    {
        //获取标品对应的供应商信息
        $noRate = false;//是否启用帮地接价格
        if(!empty($standard['supplier_admin_id']) && !empty($supplier_id)){
            $supplierAdminInfo = (new Common())->getSupplierAdminInfo($standard['supplier_admin_id']);
            if(!empty($supplierAdminInfo['company_id']) && $supplierAdminInfo['company_id']==$supplier_id){
                $noRate = true;
            }
        }

        return $noRate;

    }

    public function getStandardIdsBytagIds($tagIds)
    {
        if(empty($tagIds)) return [];
        $standardtags = db("standardtags")->where(['tagid'=>['in',$tagIds]])->field("sid,count(sid) as count");
        $standard_id_arr = $standardtags->group("sid")->select();

        $standard_id_arr =  !empty($standard_id_arr)?array_unique(array_column($standard_id_arr,"sid")):[];
        return $standard_id_arr;
    }

    //tob标品的顶层分类和标签映射 不允许添加修改
    public function getStandardTopCates()
    {
        return [
            ['id'=>1,'name'=>'景点线路','tagTypeIds'=>"5,6"],
            ['id'=>2,'name'=>'当地玩乐','tagTypeIds'=>"8"],
            ['id'=>3,'name'=>'特色商品','tagTypeIds'=>"9"],
        ];
    }
    //通过标品ID获取套餐的详情
    public function getCostAndPriceByStandardPersonIds($standardId,$supplierId,$personIds,$date="")
    {
        $standard = db("standard")->find($standardId);
        if(empty($standardId) || empty($standard)){
            return json_encode(['code'=>400,'msg'=>'标品暂未上架']);
        }
        //判断是否启用帮地接设置的利润
        $noRate = $this->verifyBdjRate($standard,$supplierId);
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;
        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //获取折扣
//        $discount_rate = $this->getDiscountRatePriceToB($standard_id);
        $discount_rate = 1;
        //viator 产品
        if(!empty($goods['third_code']) && $goods['show']==2){
            //检查是否有售卖日期
            if(empty($date)){
                return ['code'=>400,'msg'=>'viator产品需要添加date参数'];
            }
            $where_name['code'] = $goods['third_code'];
            $specsName = db('specsname')->where($where_name)->select();
            $nameArr = array();
            if(!empty($specsName)){
                foreach ($specsName as $k_name=>$v_name){
                    $nameArr[$v_name['grade_code']] = $v_name['new_name'];
                }
            }

            $data = cache($goods['third_code'].'price');
            if(empty($data)){
                return ['code'=>400,'msg'=>'商品未配置价格'];
            }else{
                unset($data['month_num']);//去除非数组的键值
                foreach ($data as $s=>$value){
                    foreach ($value as $k=>$v) {
                        if($v['bookingDate']==$date){
                            $specs = [];
                            foreach ($v['ageBands'] as $k_a=>$v_a) {
//                                if(in_array($k_a,$personIds)){
                                    $vaitor_price = ceil($v_a['price']*100)/100;
                                    $vaitor_cny_price = ceil($v_a['price']*$local_exchange*100)/100;
                                    $specs[] = [
                                        'personId'=>$k_a,
                                        'specId'=>$v_a['bandId'],
                                        'specName'=>$v_a['description'],
                                        'specStock'=>999,
                                        'specPersonsIncUnit'=>1,
                                        'specPersonsPerUnit'=>1,
                                        'specMarketPricePerPerson'=>$vaitor_price,
                                        'specPricePerPerson'=>$vaitor_price,
                                        'specMarketPricePerPersonCNY'=>$vaitor_cny_price,
                                        'specPricePerPersonCNY'=>$vaitor_cny_price,
                                    ];
//                                }
                            }
                            $packages[] = [
                                'packageId'=>0,
                                'packageName'=>$s,
                                'specs'=>$specs
                            ];
                        }
                    }
                }
            }
            if(empty($packages)) return ['code'=>400,'msg'=>'商品暂未配置价格'];
            //如果存在重复日期的套餐进行合并
            $dates = [];
            foreach ($packages as $package_k=>$package_v){
                if(!in_array($package_v['packageName'],$dates)){
                    $dates[$package_k] = $package_v['packageName'];
                }else{
                    $package_index = array_search($package_v['packageName'],$dates);
                    $packages[$package_index]['specs'] = array_merge($packages[$package_index]['specs'],$package_v['specs']);
                    unset($packages[$package_k]);
                }
            }

            $result['typesource'] = 'viator';
//            $res_data['packages'] = $packages;
            $res_data['specs'] = $packages[$personIds[0]]['specs'] ?? [];
            $res_data['discount_rate'] = $discount_rate;//不启用 折扣模式
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;
        }
        //fareahabor 产品
        if(!empty($goods['standard_pro']) && $goods['channel_source']=='fareharbor'){
            //检查是否有售卖日期
            if(empty($date)){
                return ['code'=>400,'msg'=>'fareharbor产品需要添加date参数'];
            }
            $faregoods = db("fareharbor_goods")->find($goods['source_id']);
            if(empty($faregoods)) return ['code'=>400,'msg'=>'暂未配置套餐价格'];
            $company = $faregoods['company'];
            $item = $faregoods['item_id'];
            $currency_code = (new Fmodel())->getCompanyCurrency($company);
            $exchangeArr = db("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
            $packages = (new F())->getPackageByOneDay($company,$item,$local_exchange,$date,$personIds);
            if(empty($packages)) return ['code'=>400,'msg'=>'暂未配置当日套餐价格'];
//            $res_data['packages'] = $packages;
            $res_data['specs'] = $packages[0]['specs'] ?? [];
            $res_data['discount_rate'] = $discount_rate;//不启用 折扣模式
            $res_data['typesource'] = 'fareharbor';
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;
        }
        //产品价格替换
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode,kbx_set_market_price")->find();
            if(!empty($product) && $product['base_price_mode']==1) {
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        if($goods['orderType']=="FeaturedProduct"){
            //date = 当前时间 personId为当前数据
            $date = date("Y-m-d");
            if($product_price_exists==2){
                $where_person['product_id'] = $product['id'];
                $where_person['time'] = $date;
                $personIds = db('product_base_dailyprice')
                    ->where($where_person)->column('id');
            }elseif($product_price_exists==1){
                $where_person['product_id'] = $product['id'];
                $where_person['time'] = $date;
                $personIds = db('product_dailyprice')
                    ->where($where_person)->column('id');
            }else{
                $where_person['goods_id'] = $goods['goods_id'];
                $where_person['time'] = $date;
                $personIds = db('personday')
                    ->where($where_person)->column('id');
            }
        }else{
            if(empty($personIds)) return ['code'=>400,'msg'=>'缺少规格ID集合'];
        }
        if($product_price_exists==2){
            $where_p['pd.product_id']  = $product['id'];
            $where_p['pd.id']    = ['in',$personIds];
            $total_cost = $noRate?'pd.total_cost as specPricePerPerson':'pd.total_cost*100/(100-ps.bdj_rate) as specPricePerPerson';
            //获取规格
            $personday = db('product_base_dailyprice pd')
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->where($where_p)
                ->field('pd.id as personId,pd.name as specName,pd.total_cost as specCostPerPerson,'.$total_cost.',pd.price as specMarketPricePerPerson,pd.num as specStock,pd.package_id as packageId,pd.specs_id as specId,pd.minorder_num as specPersonsPerUnit,pd.inc_order_num as specPersonsIncUnit,time')
                ->order('pd.time asc,pd.specs_id asc')
                ->select();
        }elseif($product_price_exists==1){
            $where_p['product_id']  = $product['id'];
            $where_p['pd.id']    = ['in',$personIds];
            //获取规格
            $personday = db('product_dailyprice')
                ->where($where_p)
                ->field('id as personId,name as specName,price as specCostPerPerson,price as specPricePerPerson,num as specStock,package_id as packageId,specs_id as specId,minorder_num as specPersonsPerUnit,inc_order_num as specPersonsIncUnit,time')
                ->order('time asc,specs_id asc')
                ->select();
        }else{
            //获取规格
            $where['goods_id'] = $goods['goods_id'];
            $where['id'] = ['in',$personIds];
            $personday =  db('personday')
                ->where($where)
                ->field('id as personId,person_name as specName,person_price as specCostPerPerson,person_price as specPricePerPerson,person_num as specStock,specs_id as packageId,person_id as specId,minorder_num as specPersonsPerUnit,inc_order_num as specPersonsIncUnit,time')
                ->order('time asc,id asc')
                ->select();
        }

        //汇率问题
        $exchange_rate = 1;
        if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
            $exchange_rate = $exchangeRate['exchange_rate']??$exchange_rate;
        }
        foreach ($personday as $p_k=>$p_v){
            if($product_price_exists==2){
                //默认人民币汇率
                $personday[$p_k]['specPricePerPersonCNY'] = $personday[$p_k]['specPricePerPerson'] = ceil($p_v['specPricePerPerson']);
                $personday[$p_k]['specCostPerPersonCNY'] = $personday[$p_k]['specCostPerPerson'] = ceil($p_v['specCostPerPerson']);
                $personday[$p_k]['specMarketPricePerPersonCNY'] = $personday[$p_k]['specMarketPricePerPerson'] = ceil($p_v['specMarketPricePerPerson']);
                if($exchange_rate > 1){
                    $personday[$p_k]['specPricePerPersonCNY'] = ceil(round($p_v['specPricePerPerson'])*$exchange_rate);
                    $personday[$p_k]['specCostPerPersonCNY'] = ceil(round($p_v['specCostPerPerson'])*$exchange_rate);
                    $personday[$p_k]['specMarketPricePerPersonCNY'] = ceil(round($p_v['specMarketPricePerPerson'])*$exchange_rate);
                }
            }else{
                $personday[$p_k]['specMarketPricePerPersonCNY'] = '';
                $personday[$p_k]['specMarketPricePerPerson'] = '';
                $personday[$p_k]['specPricePerPersonCNY'] = $personday[$p_k]['specPricePerPerson'] = ceil($p_v['specPricePerPerson']);
                $personday[$p_k]['specCostPerPersonCNY'] = $personday[$p_k]['specCostPerPerson'] = ceil($p_v['specCostPerPerson']);
            }
        }

        $data = [];
        $data['specs'] = $personday;
        $data['basePricrMode'] = !empty($product['base_price_mode'])?true:false;
        $data['newPriceMode'] = !empty($product['new_price_flag'])?true:false;
        $data['bdjSetMarketPrice'] = !empty($product['kbx_set_market_price'])?true:false;
        $data['currency'] = !empty($product['currency'])?$product['currency']:"CNY";
        $data['typesource'] = 'myself';
        $data['exchangeRate'] = $exchange_rate;

        return $data;
    }

    //首次上架的标品调用提醒接口
    public function setOnSaleNoticeAtFirst($standardId,$supplier_admin_name='')
    {
        if(empty($standardId)) return false;
        $standard = db('standard s')->field('s.*,st.trip_id,
            g.goods_tcode,g.orderType,p.service_type,p.supplier_id,p.supplier_item_code,p.tag_id')
            ->join('standardtrip st','st.sid=s.id','left')
            ->join('product p','p.id=st.trip_id','left')
            ->join('goods g','g.goods_id=s.goods_id','left')
            ->where(['s.id'=>$standardId])->find();
        if(empty($standard)) return false;
        //查询是否日期已过
        if($standard['creattime'] < strtotime('2020-09-16')) return false;
        //若存在 表示不是第一次提醒
        $newStandard = db('standard_first_onsale_notice')->where('standard_id',$standardId)->find();
        if(!empty($newStandard)) return false;

        $productTags = db('standardtags')->where('sid',$standard['id'])->order('sort asc')->column('tagid');
        $productTags = array_values(array_filter(array_merge($productTags,explode(',',$standard['tag_id']))));
        $tagNames = [];
        if(!empty($productTags)){
            $tagNames = db('tag')->where(['tag_id'=>['in',$productTags],'tag_status'=>1])->column('tag_name');
        }
        $postdata['productTags'] = implode(',',$tagNames);
        $postdata['adminName'] = '';
        if(!empty($supplier_admin_name)){
            $postdata['adminName'] = $supplier_admin_name;
        }else{
            $admin_id = Cookie::get('admin');
            $adminInfo = (new Common())->getAdminInfo($admin_id);
            if(!empty($adminInfo['nickname'])) $postdata['adminName'] = $adminInfo['nickname'];
        }

        $postdata['standardId'] = $standard['id'];
        $postdata['productCode'] = $standard['goods_tcode'];
        $postdata['productName'] = $standard['name'];
        $cityName = '';
        if(!empty($standard['startCity'])){
            $cityName = db('city')->field('name')->find($standard['startCity'])['name']??'';
        }
        $postdata['city'] = $cityName;
        $serviceType = '';
        if(!empty($standard['service_type'])){
            $serviceType = db('service_type')->field('type')->find($standard['service_type'])['type']??'';
        }else{
            $serviceType = $standard['orderType']??'';
        }
        $postdata['serviceType'] = $serviceType;
        $supplierName = '';
        if(!empty($standard['supplier_id'])){
            $supplierList = (new Common())->getSupplierList();
            foreach ($supplierList as $value){
                if($value['id'] == $standard['supplier_id']){
                    $supplierName = $value['name'];
                    break;
                }
            }
        }

        $postdata['supplier'] = $supplierName;
        //记录日志 如果存在记录则抛出错误
        db::startTrans();
        try{
            db('standard_first_onsale_notice')->insert([
                'standard_id'=>$standardId,
                'notice_time'=>time()
            ]);
            db::commit();
        }catch(DbException $e){
            db::rollback();
            trace('重复插入提醒：'.$e->getMessage());
            return false;
        }

        $res = (new KbxOrder())->postNewToBProductNotify($postdata);

        if(isset($res['msg'])){
            trace('首次上架的标品接口报错！数据为'.json_encode($postdata));
            return false;
        }else{
            return $res;
        }
    }

    //更新标品调用提醒接口 上架主动调用 下架或者更新提示是否调用
    public function putOnSaleNotifyV2ToKbx($standardId,$extraText="")
    {
        $fromKbxCity = "";
        $standardName = "";
        $typeSource = "myself";
        $standardType = '2';
        $standard = db('standard')->find($standardId);
        if(!empty($standard['goods_id'])){
            $standardName = $standard['name'] ?? $standardName;
            $standardType = $standard['type'] ?? $standardType;
            $goods = db('goods')->find($standard['goods_id']);
            $city = db('city')->find($standard['startCity']);
            if(!empty($goods)){
                if($goods['show']==2){
                    $typeSource = 'viator';
                }else{
                    $typeSource = !empty($goods['channel_source']) ? $goods['channel_source'] : 'myself';
                }
            }
            if(!empty($city)){
                $fromKbxCity = $city['kbx_id'] ?? '';
            }
        }

        $post_data['standardId'] = $standardId;
        $post_data['name'] = $standardName;
        $post_data['fromCity'] = $fromKbxCity;
        $post_data['extraText'] = $extraText;
        $post_data['standardType'] = $standardType;
        $post_data['typeSource'] = $typeSource;

        $res = (new KbxOrder())->putOnSaleNotifyV2ToKbx($post_data);
        if(isset($res['msg'])){
            trace('更新标品调用提醒接口报错！数据为'.json_encode($post_data));
        }

        return $res;
    }

    //图片统一处理格式 自动缩放尺寸 700:420 自动补全空白
    public function batchOssImgUrl($img,$width=700,$height=420)
    {
        if(empty($img)) return is_array($img) ? [] : '';
        $suffix = '?x-oss-process=image/resize,w_'.$width.',h_'.$height.',m_pad/auto-orient,1/quality,q_90/format,jpg';
        if(is_array($img)){
            foreach ($img as $key=>$value){
                if(!empty($value)) $img[$key] = $value.$suffix;
            }
            return $img;
        }else{
            return $img.$suffix;
        }
    }

    //更新标品库存
    public function updateStandardStock($goodsId,$packages,$type='dec')
    {
        if(empty($goodsId)) return false;
        $standard = db("standard")->where(['goods_id'=>$goodsId])->find();
        if(empty($standard)) return false;
        $goods = $this->checkExistGoods($goodsId);
        if(isset($goods['code'])) return false;
        if(empty($packages['specs'])) return false;
        //产品价格替换
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode,kbx_set_market_price")->find();
            if(!empty($product) && $product['base_price_mode']==1) {
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        $updateStock = true;
        db::startTrans();
        try{
            //非特色商品的库存优化
            foreach ($packages['specs'] as $key=>$value){
                if(!empty($value['buyCount']) && !empty($value['personId'])){
                    //还原库存直接操作
                    if($type=='inc'){
                        $updateStock = $this->updateStandardStockByPersonId($goods['orderType'],$product_price_exists,$value['personId'],$value['buyCount'],$type);
                        if(!$updateStock) break;
                    }else{
                        //先查库存 然后更新
                        $stock = $this->getStandardStockByPersonId($product_price_exists,$value['personId']);
                        if($value['buyCount'] <= $stock){
                            $updateStock = $this->updateStandardStockByPersonId($goods['orderType'],$product_price_exists,$value['personId'],$value['buyCount'],'dec');
                            if(!$updateStock) break;
                        }else{
                            $updateStock = false;break;
                        }
                    }
                }else{
                    continue;
                }
            }
            db::commit();
            trace('接口更新库存成功');
            return $updateStock;

        }catch(\Exception $e){
            db::rollback();
            trace('接口更新库存失败'.$e->getMessage());
            return false;
        }

    }
    //获取当前的最新的库存信息
    public function getStandardStockByPersonId($product_price_exists,$personId)
    {
        if($product_price_exists==2){
            $where_person['id'] = $personId;
            $stock = db('product_base_dailyprice')->field('num as stock')
                ->where($where_person)->find();
        }elseif($product_price_exists==1){
            $where_person['id'] = $personId;
            $stock = db('product_dailyprice')->field('num as stock')
                ->where($where_person)->find();
        }else{
            $where_person['id'] = $personId;
            $stock = db('personday')->field('person_num as stock')
                ->where($where_person)->find();
        }
        return empty($stock['stock']) ? 0 : $stock['stock'];
    }
    //更新当前的最新的库存信息
    public function updateStandardStockByPersonId($orderType,$product_price_exists,$personId,$buyCount,$type='dec')
    {
        $filterOrderType = in_array($orderType,["FeaturedProduct"]);
        $where_person['id'] = $personId;

        if($product_price_exists==2){
            if($filterOrderType){
                $priceData = db('product_base_dailyprice')->where($where_person)->find();
                $where_person = [];
                $where_person['specs_id'] = $priceData['specs_id'];
                $spec_stock_res = $type == 'dec' ?
                    db('product_base_specs')->where(['id'=>$priceData['specs_id']])->setDec('num',$buyCount) :
                    db('product_base_specs')->where(['id'=>$priceData['specs_id']])->setInc('num',$buyCount) ;
            }
            $stock_res = $type == 'dec' ?
                db('product_base_dailyprice')->where($where_person)->setDec('num',$buyCount) :
                db('product_base_dailyprice')->where($where_person)->setInc('num',$buyCount) ;

        }elseif($product_price_exists==1){
            if($filterOrderType){
                $priceData = db('product_dailyprice')->where($where_person)->find();
                $where_person = [];
                $where_person['specs_id'] = $priceData['specs_id'];
                $spec_stock_res = $type == 'dec' ?
                    db('product_specs')->where(['id'=>$priceData['specs_id']])->setDec('num',$buyCount) :
                    db('product_specs')->where(['id'=>$priceData['specs_id']])->setInc('num',$buyCount) ;
            }
            $stock_res = $type == 'dec' ?
                db('product_dailyprice')->field('num as stock')->setDec('num',$buyCount) :
                db('product_dailyprice')->field('num as stock')->setInc('num',$buyCount) ;
        }else{
            if($filterOrderType){
                $priceData = db('personday')->where($where_person)->find();
                $where_person = [];
                $where_person['person_id'] = $priceData['person_id'];
                $spec_stock_res = $type == 'dec' ?
                    db('product_specs')->where(['person_id'=>$priceData['person_id']])->setDec('person_num',$buyCount) :
                    db('product_specs')->where(['person_id'=>$priceData['person_id']])->setInc('person_num',$buyCount) ;
            }
            $stock_res = $type == 'dec' ?
                db('personday')->where($where_person)->setDec('person_num',$buyCount) :
                db('personday')->where($where_person)->setInc('person_num',$buyCount) ;
        }
        return $stock_res;
    }

    //采购商获取套餐详情
    public function getGoodsPackageSpecsToOTA($standard_id,$supplier_id)
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'暂未查询到相关标品'];
        }
        //判断是否启用帮地接设置的利润
        $noRate = $this->verifyBdjRate($standard,$supplier_id);
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;

        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        //$exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        //$local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //获取折扣
        //$discount_rate = $this->getDiscountRatePriceToB($standard_id);
        $discount_rate = 1;
        //Viator商品
        if(!empty($goods['third_code']) && $goods['show']== 2){
            $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate']??1;//当地汇率    美元/加元
            $data= cache($goods['third_code'].'price');
            if(empty($data)){
                return ['code'=>400,'msg'=>'暂未查询到viator产品的价格数据！'];
            }else{
                unset($data['month_num']);//去除非数组的键值
                //获取viator套餐自定义名称
                list($viatorPackageNameArr,$specNameArr) = (new Standard())->getViatorSpecsDIY($goods['third_code']);
                foreach ($data as $s=>$value){
                    $bandIds = [];
                    foreach ($value as $k=>$v) {
                        foreach ($v['ageBands'] as $k_a=>$v_a) {
                            if(!in_array($v_a['bandId'],$bandIds)){
                                $bandIds[] = $v_a['bandId'];
                                $viatorPrice = ceil($v_a['price']*100)/100;
                                $viatorPriceCNY = ceil($v_a['price']*$local_exchange*100)/100;
                                $packages[] = [
                                    'specId'=>$v_a['bandId'],
                                    'specName'=>!empty($specNameArr[$v_a['description']])?$specNameArr[$v_a['description']]:$v_a['description'],
                                    'specStock'=>999,
                                    'specPersonsIncUnit'=>1,
                                    'specPersonsPerUnit'=>1,
                                    'specMarketPricePerPerson'=>$viatorPrice,
                                    'specMarketPricePerPersonCNY'=>$viatorPriceCNY,
                                    'specPricePerPerson'=>$viatorPrice,
                                    'specPricePerPersonCNY'=>$viatorPriceCNY,
                                ];
                            }

                        }
                    }
                    $res_data['packages'] = $packages;
                }
            }
            $res_data['typesource'] ='viator';
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = $currency_code;
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;

        }

        //检查商品类型
        if(!empty($goods['standard_pro']) && $goods['channel_source']=='fareharbor'){
            $faregoods = db("fareharbor_goods")->find($goods['source_id']);
            if(empty($faregoods)) return ['code'=>400,'msg'=>'暂未查询到关联的fareharbor产品'];
            //获取farehabor利润点
            $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
            $sell_percent_rate = empty($sell_rate)&&$sell_rate['discount_num']?1:$sell_rate['discount_num'];
            $company = $faregoods['company'];
            $currency_code = (new FModel())->getCompanyCurrency($company);
            $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate']??1;//当地汇率    美元/加元
            $item = $faregoods['item_id'];
            $items = (new FModel())->getFareharborData(['company'=>$company]);
            $specsName = db('faregoods_specname')->where('item_id',$item)->select();
            $specs = [];
            foreach ($items as $value){
                if($value['pk']==$item){
                    foreach ($value['customer_prototypes'] as $customer_price){
                        $display_name = "";
                        foreach ($specsName as $s_name){
                            if($s_name['en_name']==$customer_price['display_name']){
                                $display_name = $s_name['ch_name'];break;
                            }
                        }
                        //total_including_tax 单位美分
                        $fareharbor_price = ceil($customer_price['total_including_tax']*$sell_percent_rate)/100;
                        $fareharbor_price_cny = ceil($customer_price['total_including_tax']*$local_exchange*$sell_percent_rate)/100;
                        $specs[] = [
                            'specId'=>$customer_price['pk'],
                            'specName'=>!empty($display_name)?$display_name:$customer_price['display_name'],
                            'specStock'=>999,
                            'specPersonsIncUnit'=>1,
                            'specPersonsPerUnit'=>1,
                            'specMarketPricePerPerson'=>$fareharbor_price,
                            'specMarketPricePerPersonCNY'=>$fareharbor_price_cny,
                            'specPricePerPerson'=>$fareharbor_price,
                            'specPricePerPersonCNY'=>$fareharbor_price_cny,
                        ];
                    }

                }
            }
            if(empty($specs)){
                return ['code'=>400,'msg'=>'暂未查询到farehabor产品的价格数据！'];
            }
            $res_data['typesource'] ='fareharbor';
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            $res_data['packages'] = $specs;

            return $res_data;
        }

        $product_price_exists = 0;//价格模式标志
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,service_type,price_section,new_price_flag,base_price_mode,kbx_set_market_price")->find();
            if(!empty($product) && $product['base_price_mode']==1) {
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        //汇率问题
        $local_exchange = 1;
        //用车类产品价格统一为人民币
        if(!empty($product['service_type']) && $product['service_type']==5) $product['currency'] = 'CNY';
        if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
            $local_exchange = $exchangeRate['exchange_rate']??$local_exchange;
        }
        if($product_price_exists==2){
            //获取套餐
            $specs = db('product_base_specs ps')
                ->join('product_base_package pp','pp.id=ps.package_id','left')
                ->where(['pp.product_id'=>$product['id']])
                ->where('ps.status',1)
                ->field('ps.id as specId,ps.name as specName,
                ps.num as specStock,ps.inc_order_num as specPersonsIncUnit,
                ps.minorder_num as specPersonsPerUnit,ps.package_id as packageId,
                pp.name as packageName,ps.special as isIgnore')
                ->select();

        }elseif($product_price_exists==1){
            //获取套餐
            $specs = db('product_specs ps')
                ->join('product_package pp','pp.id=ps.package_id','left')
                ->where(['pp.product_id'=>$product['id']])
                ->where('ps.status',1)
                ->field('ps.id as specId,ps.name as specName,
                ps.num as specStock,ps.inc_order_num as specPersonsIncUnit,
                ps.minorder_num as specPersonsPerUnit,ps.package_id as packageId,
                pp.name as packageName,"0" as isIgnore')
                ->select();

        }else{
            //获取套餐
            $specs = db('person ps')
                ->join('specs pp','pp.specs_id=ps.specs_id','left')
                ->where(['pp.goods_id'=>$goods_id])
                ->where('ps.person_status',1)
                ->field('ps.person_id as specId,ps.person_name as specName,
                ps.person_num as specStock,ps.inc_order_num as specPersonsPerUnit,
                ps.minorder_num as specPersonsPerUnit,ps.specs_id as packageId,
                pp.specs_id as packageName,"0" as isIgnore')
                ->select();

        }

        $data['typesource'] ='myself';
        $data['basePricrMode'] = !empty($product['base_price_mode'])?true:false;
        $data['newPriceMode'] = !empty($product['new_price_flag'])?true:false;
        $data['bdjSetMarketPrice'] = !empty($product['kbx_set_market_price'])?true:false;
        $data['currency'] = !empty($product['currency'])?$product['currency']:'CNY';
        $data['exchangeRate'] = $local_exchange;
        $data['packages'] = $specs;
        return $data;
    }

    //获取商品套餐日历价格
    public function getGoodsSpecToOTA($standard_id,$year='',$month='',$duration=1,$supplier_id='')
    {
        $standard = db("standard")->find($standard_id);
        if(empty($standard_id) || empty($standard)){
            return ['code'=>400,'msg'=>'标品暂未上架'];
        }
        //判断是否启用帮地接设置的利润
        $noRate = $this->verifyBdjRate($standard,$supplier_id);
        $goods_id = $standard['goods_id']??0;
        $goods = $this->checkExistGoods($goods_id);
        if(isset($goods['code'])) return $goods;
        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        $currency_code = "USD";//默认美元
        if($goods['city_groupid']==51){//加拿大
            $currency_code = "CAD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
        //获取折扣
//        $discount_rate = $this->getDiscountRatePriceToB($standard_id);
        $discount_rate = 1;
        //检查商品类型
        if(!empty($goods['standard_pro']) && $goods['channel_source']=='fareharbor'){
            $faregoods = db("fareharbor_goods")->find($goods['source_id']);
            if(empty($faregoods)) return ['code'=>400,'msg'=>'商品未上架'];
            $company = $faregoods['company'];
            $item = $faregoods['item_id'];
            $currency_code = (new Fmodel())->getCompanyCurrency($company);
            $exchangeArr = db("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元
            $packages = (new F())->getPackageByLastMonth($company,$item,$local_exchange,time(),3);
            if(empty($packages)) return ['code'=>400,'msg'=>'商品暂未配置价格'];
            $sale_time = !empty($packages[0]['time'])?$packages[0]['time']:'';
            $res_data['packages'] = $packages;
            $res_data['goods_id'] = $goods_id;
            $res_data['discount_rate'] = $discount_rate;//不启用 折扣模式
            $res_data['type'] = 'fareharbor';
            $res_data['sale_time'] = $sale_time;
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;
        }

        //Viator商品
        if(!empty($goods['third_code']) && $goods['show']== 2){
            $data = cache($goods['third_code'].'price');
            if(empty($data)){
                return ['code'=>400,'msg'=>'商品未配置价格'];
            }else{
                unset($data['month_num']);//去除非数组的键值
                //获取viator套餐自定义名称
                list($viatorPackageNameArr,$specNameArr) = (new Standard())->getViatorSpecsDIY($goods['third_code']);
                foreach ($data as $s=>$value){
                    foreach ($value as $k=>$v) {
                        $specs = [];
                        foreach ($v['ageBands'] as $k_a=>$v_a) {
                            $vaitor_price = ceil($v_a['price']*100)/100;
                            $vaitor_cny_price = ceil($v_a['price']*$local_exchange*100)/100;
                            $specs[] = [
                                'packageId'=>0,
                                'packageName'=>!empty($viatorPackageNameArr[$s])?$viatorPackageNameArr[$s]:$s,
                                'specId'=>$v_a['bandId'],
                                'specName'=>!empty($specNameArr[$v_a['description']])?$specNameArr[$v_a['description']]:$v_a['description'],
                                'specStock'=>999,
                                'specPersonsIncUnit'=>1,
                                'specPersonsPerUnit'=>1,
                                'specMarketPricePerPerson'=>$vaitor_price,
                                'specPricePerPerson'=>$vaitor_price,
                                'specMarketPricePerPersonCNY'=>$vaitor_cny_price,
                                'specPricePerPersonCNY'=>$vaitor_cny_price,
                            ];
                        }
                        $packages[] = [
                            'time'=>$v['bookingDate'],
                            'specs'=>$specs
                        ];
                    }
                }
            }
            if(empty($packages)) return ['code'=>400,'msg'=>'商品暂未配置价格'];
            //如果存在重复日期的套餐进行合并
            $dates = [];
            foreach ($packages as $package_k=>$package_v){
                if(!in_array($package_v['time'],$dates)){
                    $dates[$package_k] = $package_v['time'];
                }else{
                    $package_index = array_search($package_v['time'],$dates);
                    $packages[$package_index]['specs'] = array_merge($packages[$package_index]['specs'],$package_v['specs']);
                    unset($packages[$package_k]);
                }
            }

            $sale_time = !empty($packages[0]['time'])?$packages[0]['time']:'';
            $res_data['packages'] = $packages;
            $res_data['goods_id'] = $goods_id;
            $res_data['discount_rate'] = $discount_rate;//不启用 折扣模式
            $res_data['type'] = 'viator';
            $res_data['sale_time'] = $sale_time;
            $res_data['basePricrMode'] = false;
            $res_data['newPriceMode'] = false;
            $res_data['bdjSetMarketPrice'] = false;
            $res_data['currency'] = strtoupper($currency_code);
            $res_data['exchangeRate'] = $local_exchange;
            return $res_data;
        }

        //产品价格替换
        $product_id = '';
        $product_section = '';
        $product_price_exists = 0;//是否存在产品价格
        $bdjSetMarketPrice = 0;//设置统一售价
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode,kbx_set_market_price")->find();
            if(!empty($product) && $product['base_price_mode']==1){
                $product_id = $product['id'];
                $product_price_exists = 2;//存在产品设置基础价格
            }elseif(!empty($product) && $product['new_price_flag']==1){
                $product_id = $product['id'];
                $product_price_exists = 1;//存在产品设置价格
            }
        }
        //获取可售卖的时间 截止天数+当前时间
        //地接社类标品
        if(!empty($standard['s_endDays'])){
            $sale_time = $standard['s_endDays']==1?strtotime('+1 day'):strtotime('+'.$standard['s_endDays'].' days');
        }else{
            $standardtrip = db('standardtrip')->where('sid',$standard_id)->find();
            if(!empty($standardtrip['endDays']) && $standardtrip['endDays']>0){
                $sale_time = $standardtrip['endDays']==1?strtotime('+1 day'):strtotime('+'.$standardtrip['endDays'].' days');
            }else{
                $sale_time = time();
            }
        }
        $sale_time = date('Y-m-d',$sale_time);
        $start_day = $end_day = '';
        if(!empty($year) && !empty($month)){
            $month = $month < 10 ? '0'.$month : $month;
            $start_day = $year.'-'.$month.'-01';
            $start_time = strtotime($start_day);
            $end_day = date("Y-m-d",strtotime('+'.$duration.' months',$start_time));
            $start_day = max([$sale_time,$start_day]);//获取比较大的起始日期
        }
        $where = [];
        if($product_price_exists==2){
            $where['pd.product_id'] = $product_id;
            //获取所有的日期的价格设置
            $total_cost = $noRate?'pd.total_cost as specPricePerPerson':'pd.total_cost*100/(100-ps.bdj_rate) as specPricePerPerson';
            if(!empty($start_day) && !empty($end_day)){
                $where['pd.time'] = [['egt',$start_day],['lt',$end_day]];
            }else{
                $where['pd.time'] = ['egt',$sale_time];
            }
            $personday = db('product_base_dailyprice pd')
                ->join('product_base_package pp','pp.id=pd.package_id','left')
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->where($where)
                ->field("pp.name as packageName,pd.name as specName,".$total_cost.",pd.price as specMarketPricePerPerson,pd.num as specStock,pd.package_id as packageId,pd.specs_id as specId,pd.minorder_num as specPersonsPerUnit,pd.inc_order_num as specPersonsIncUnit,time")
                ->order("pd.time asc")
                ->select();

        }elseif($product_price_exists==1){
            $where['pd.product_id'] = $product_id;
            //获取所有的日期的价格设置
            if(!empty($start_day) && !empty($end_day)){
                $where['pd.time'] = [['egt',$start_day],['lt',$end_day]];
            }else{
                $where['pd.time'] = ['egt',$sale_time];
            }
            //获取所有的日期的价格设置
            $personday = db('product_dailyprice pd')
                ->join('product_package pp','pp.id=pd.package_id','left')
                ->where($where)
                ->field("pp.name as packageName,pd.name as specName,
                pd.price as specPricePerPerson,pd.num as specStock,
                pd.package_id as packageId,pd.specs_id as specId,
                pd.minorder_num as specPersonsPerUnit,
                pd.inc_order_num as specPersonsIncUnit,pd.time")
                ->order("pd.time asc")
                ->select();
        }else{
            $where['goods_id'] = $goods_id;
            //获取所有的日期的价格设置
            if(!empty($start_day) && !empty($end_day)){
                $where['time'] = [['egt',$start_day],['lt',$end_day]];
            }else{
                $where['time'] = ['egt',$sale_time];
            }
            //获取所有的日期的价格设置
            $personday = db('personday p')
                ->join('specs ss','ss.specs_id=p.specs_id','left')
                ->where($where)
                ->field("ss.specs_name as PackageName,p.person_name as specName,p.person_price as specPricePerPerson,p.person_num as specStock,p.specs_id as packageId,p.person_id as specId,p.minorder_num as specPersonsPerUnit,p.inc_order_num as specPersonsIncUnit,time")
                ->order("time asc")
                ->select();
        }
        if(empty($personday)) return ['code'=>400,'msg'=>'暂未配置价格'];
        //汇率问题
        $exchange_rate = 1;
        if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
            $exchange_rate = $exchangeRate['exchange_rate']??$exchange_rate;
        }
        foreach ($personday as $p_k=>$p_v){
            if($product_price_exists==2){
                //默认人民币汇率
                $personday[$p_k]['specPricePerPersonCNY'] = $personday[$p_k]['specPricePerPerson'] = ceil($p_v['specPricePerPerson']);
                $personday[$p_k]['specMarketPricePerPersonCNY'] = $personday[$p_k]['specMarketPricePerPerson'] = ceil($p_v['specMarketPricePerPerson']);
                if($exchange_rate > 1){
                    $personday[$p_k]['specPricePerPersonCNY'] = ceil(round($p_v['specPricePerPerson'])*$exchange_rate);
                    $personday[$p_k]['specMarketPricePerPersonCNY'] = ceil(round($p_v['specMarketPricePerPerson'])*$exchange_rate);
                }
            }else{
                $personday[$p_k]['specMarketPricePerPersonCNY'] = '';
                $personday[$p_k]['specMarketPricePerPerson'] = '';
                $personday[$p_k]['specPricePerPersonCNY'] = $personday[$p_k]['specPricePerPerson'] = ceil($p_v['specPricePerPerson']*$discount_rate);
            }
        }

        $packages = [];
        $specIds = [];
        foreach ($personday as $person_key=>$person_value){
            if(!in_array($person_value['specId'],$specIds)){
                $specIds[] = $person_value['specId'];
                $packages[] = [
                    'packageName'=>$person_value['packageName'],
                    'packageId'=>$person_value['packageId'],
                    'specId'=>$person_value['specId'],
                    'specName'=>$person_value['specName'],
                    'prices'=>[]
                ];
            }
        }
        foreach ($packages as $p_key=>$p_value){
            foreach ($personday as $person_key=>$person_value){
                if($person_value['specId']==$p_value['specId']){
                    unset($person_value['packageId'],$person_value['specId'],$person_value['specName']);
                    $packages[$p_key]['prices'][] = $person_value;
                }
            }
        }
        if(empty($packages)) return ['code'=>400,'msg'=>'暂未配置价格'];
//        foreach ($days as $day_key=>$day_value){
//            $saleNum = [];
//            $price = [];
//            foreach ($day_value['specs'] as $specs){
//                $saleNum[] = $specs['specStock'];
//                $price[] = $product_price_exists==2?round($specs['specPricePerPerson']):ceil($specs['specPricePerPerson']*$discount_rate);
//            }
//            $min_price = 0;
//            $min_salenum = 0;
//            if(!empty($price)){
//                $min_price = min($price);
//                $min_key = array_search($min_price,$price);
//                $min_salenum = $saleNum[$min_key];
//            }
//            $days[$day_key]['minPrice'] = $min_price;
//            $days[$day_key]['minStock'] = $min_salenum;
//            unset($days[$day_key]['specs']);
//        }
        $data['packages'] = $packages;
        $data['goods_id'] = $goods_id;
        $data['discount_rate'] = $discount_rate;
        $data['type'] = 'myself';
        $data['sale_time'] = $sale_time;
        $data['basePricrMode'] = !empty($product['base_price_mode'])?true:false;
        $data['newPriceMode'] = !empty($product['new_price_flag'])?true:false;
        $data['bdjSetMarketPrice'] = !empty($product['kbx_set_market_price'])?true:false;
        $data['currency'] = !empty($product['currency'])?$product['currency']:'CNY';
        $data['exchangeRate'] = $exchange_rate;
        return $data;
    }

    //读取详情
    public function infoGuide($id,$supplier_admin_id=[])
    {
        $info = db('supplier_travel_guides')
//            ->where(['supplier_admin_id'=>['in',$supplier_admin_id]])
            ->find($id);
        if(empty($info)) return [];
        if(!empty($info['link_poi_ids'])){
            $info['poies'] = db('poi')->where(['id'=>['in',$info['link_poi_ids']]])
                ->field('id,name,eng_name,groupid,introduce,lat,lng,thumb,address,create_time,update_time')
                ->order(new Expression('field(id,'.$info['link_poi_ids'].')'))
                ->select();
        }else{
            $info['poies'] = [];
        }

        $info['category_name'] = (new SupplierTravelGuides())->getCategooryTypeNameById($info['category']);
        $info['content'] = htmlspecialchars_decode($info['content']);
        $info['tagsArr'] = explode(',',$info['tags']);
        $info['show_browse'] = $info['browse'] + $info['fake_browse'];

        $info['create_time'] = date('Y-m-d H:i:s',$info['create_time']);
        $info['update_time'] = date('Y-m-d H:i:s',$info['update_time']);
        return $info;
    }

    //读取列表
    public function listGuide($where,$page,$pageLimit,$order_desc='create_time desc')
    {
        $count = db('supplier_travel_guides')->where($where)->count();
        $list = db('supplier_travel_guides')->where($where)
            ->field('id,title,description,create_time,update_time,cover_img,
                supplier_admin_id,link_poi_ids,sort_num,browse,fake_browse,category,content')
            ->order($order_desc)
            ->page($page,$pageLimit)->select();

        if(empty($list)) return [];
        foreach ($list as $key=>$value){
            if(!empty($value['link_poi_ids'])){
                $list[$key]['poies'] = db('poi')->where(['id'=>['in',$value['link_poi_ids']]])
                    ->field('id,name,eng_name,groupid,introduce,lat,lng,thumb,address')
                    ->order(new Expression('field(id,'.$value['link_poi_ids'].')'))
                    ->select();
            }else{
                $list[$key]['poies'] = [];
            }
            $list[$key]['caetgory_name'] = (new SupplierTravelGuides())->getCategooryTypeNameById($value['category']);
            $list[$key]['show_browse'] = $value['browse'] + $value['fake_browse'];
            $list[$key]['supplier_name'] = (new Common())->getSupplierAdminInfo($value['supplier_admin_id'])['supplier_name'] ?? '';
            $list[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            $list[$key]['update_time'] = date('Y-m-d H:i:s',$value['update_time']);
        }

        $result = [
            'totalCount'    => $count,
            'totalPage'     => ceil($count/$pageLimit),
            'page'          => $page,
            'pageLimit'     => $pageLimit,
            'list'          => $list
        ];
        return $result;
    }

    public function incBrowseByGuideId($id)
    {
        $info = db('supplier_travel_guides')->find($id);
        if(empty($info)) return false;
        return db('supplier_travel_guides')->where(['id'=>$id])->setInc('browse',1);
    }

    public function getViatorSpecsDIY($viator_goods_code)
    {
        //修改过的自定义套餐名称
        $where_name['code'] = $viator_goods_code;
        $specsName = db('specsname')->where($where_name)->select();
        $nameArr = array();
        if(!empty($specsName)){
            foreach ($specsName as $k_name=>$v_name){
                $nameArr[$v_name['grade_code']] = $v_name['new_name'];
            }
        }

        $cache_viator_type = cache($viator_goods_code.'type');
        foreach ($cache_viator_type as $cache_key=>$cache_value){
            if(empty($nameArr[$cache_value['gradeCode']])){
                $nameArr[$cache_value['gradeCode']] = $cache_value['specs_name']??'普通套餐';
            }
        }

        $eto_list=[
            'Adult'   => '成人',
            'Child'   => '儿童',
            'Infant'  => '婴儿',
            'Youth'   => '青年',
            'Senior'  => '老年人',
            '成年人'  => '成年人',
            '儿童'    => '儿童',
            '婴儿'    => '婴儿'
        ];

        return [$nameArr,$eto_list];
    }
    public function getViatorApiPrice($viatorData,$discount_rate)
    {
        if(empty($viatorData['currencyCode']) || empty($viatorData['price'])){
            return [0,0];
        }else{
            $exchangeArr = Db::name("exchange")->where("currency_code",$viatorData['currencyCode'])->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate'] ?? 1;//当地汇率    美元/加元
            //存在viator价格
            if(!empty($discount_rate)){
                $old_price = $viatorData['price'];
                $discount_price = $old_price*$discount_rate;
            }
            $old_price = ceil($old_price*$local_exchange);
            $old_price = strval($old_price);
            $discount_price = ceil($discount_price*$local_exchange);
            $discount_price = strval($discount_price);
            return [$discount_price,$old_price];
        }
    }
}